xxxxxxxxxx
39
let advice; //variable for json object
let button; //variable for button
//use the preload function to load the json into the variable
function preload(){
advice = loadJSON("https://api.adviceslip.com/advice")
}
//the setup function runs one time
function setup() {
createCanvas(400, 400) // create the canvas space
noLoop();
button = createButton('Get New Adivce'); //button object
button.position(width/2-50, height*3/4); //set the location of button
button.mousePressed(getNewAdvice); //function to run when button clicked
}
//the draw function runs forever, 60 frames per second
function draw() {
background('brown') //canvas background color
fill('gold')
rect(0,100,width,200) //advice area
textSize(20);
textWrap(WORD);
textFont('Georgia');
fill('black')
text(advice.slip.advice,20,125,width-20,200) //place advice on to screen using the text function
}
//function to loadJSON again
function getNewAdvice(){
loadJSON("https://api.adviceslip.com/advice",updateAdvice)
}
//function to update advice object after json is loaded
function updateAdvice(newAdvice){
advice = newAdvice //set the new Advice object to our advice variable
redraw() //reloads the draw function
}