Search code examples
javascriptloopsrandomrefreshdraw

draw function not looping as expected


I'm a beginner on here, so apologies in advance for naivety. I've made a simple image on Brackets using Javascript, trying to generate circles with random x and y values, and random colours. There are no issues showing when I open the browser console in Developer Tools, and when I save and refresh, it works. But I was expecting the refresh to happen on a loop through the draw function. Any clues as to where I've gone wrong?

Thanks so much

var r_x
var r_y
var r_width
var r_height
var x
var y
var z


function setup() 
{
    r_x = random()*500;
    r_y = random()*500;
    r_width = random()*200;
    r_height = r_width;
    x = random(1,255);
    y= random(1,255);
    z= random(1,255);

    createCanvas(512,512);
    background(255);

}

function draw()
{

    ellipse(r_x, r_y, r_width, r_height);
    fill(x, y, z);
}

Solution

  • Brackets.io is just your text editor (or IDE if you want to be technical) - so we can remove that from the equation. The next thing that baffles me is that something has to explicitly call your draw() method as well as the setup() method -

    I'm thinking that you're working in some sort of library created to simplify working with the Canvas API because in the setup() method you're calling createCanvas(xcord,ycord) and that doesn't exist on it's own. If you want to rabbit hole on that task check out this medium article, it walks you thru all the requirements for creating a canvas element and then drawing on that canvas

    Your also confirming that you're drawing at least 1 circle on browser refresh so i think all you need to focus on is 1)initiating your code on load and 2)a loop, and we'll just accept there is magic running in the background that will handle everything else.

    At the bottom of the file you're working in add this:

    // when the page loads call drawCircles(), 
    // i changed the name to be more descriptive and i'm passing in the number of circles i want to draw, 
    // the Boolean pertains to event bubbling  
    window.addEventListener("load", drawCircles(73), false);
    

    In your drawCircles() method you're going to need to add the loop:

    // im using a basic for loop that requires 3 things:
    // initialization, condition, evaluation
    // also adding a parameter that will let you determine how many circles you want to draw
    function drawCircles(numCircles) {
      for (let i = 0; i < numCircles; i++) {
        ellipse(r_x, r_y, r_width, r_height);
        fill(x, y, z);
      }
    }
    

    here's a link to a codepen that i was tinkering with a while back that does a lot of the same things you are

    I hope that helps - good luck on your new learning venture, it's well worth the climb!