Search code examples
javascriptp5.jsvisual-web-developer

How does the p5.js draw function work?


Can't work out what I'm doing wrong. Looking at the code below my logic is that each time the draw function is called the ellipse's coordinates are changed to be another random number.

However instead of the coordinates being changed, the ellipse is just being redrawn at the 'new' coordinates.

Does anyone care to shed some light on why the shape is being redrawn rather than moved? I'm using the p5 javascript library.

var frate = 10;
var elliX = 500;
var elliY = 400;

function setup() {
    createCanvas(100, 100);
    frameRate(frate);
}

function draw() {
    elliX = (random(0,100));
    elliY = (random(0,100));
    ellipse(elliX, elliY, 30);
}

Solution

  • p5 doesn't clear the canvas by default, so it's adding a new circle every time you're drawing. To clear, you can call clear() beforehand, like so:

    var frate = 10;
    var elliX = 500;
    var elliY = 400;
    
    function setup() {
        createCanvas(100, 100);
        frameRate(frate);
    }
    
    function draw() {
        clear();
        elliX = (random(0,100));
        elliY = (random(0,100));
        ellipse(elliX, elliY, 30);
    }
    <script src="https://unpkg.com/p5@0.6.1/lib/p5.min.js"></script>