Search code examples
variablesglobal-variablesp5.js

Create a global element in p5js


Is there a way to make a graphics element global, in p5js? Right now I want to make the ellipse be global:

var bug = ellipse(0, random(height), 20, 20);

function setup() {
    createCanvas(500, 500);
    background(100);

 }

function draw() {

 }

I want to store the ellipse in a variable. But there's an error saying that "mySketch.js, line 1:Uncaught ReferenceError: ellipse is not defined". Can someone help? Thanks.


Solution

  • The ellipse() function draws an ellipse, but it doesn't return anything, so you can't store the result of calling it in a variable.

    I'm not totally sure what you're trying to do, but you have a couple options worth exploring:

    1. You could store all of the values for your ellipse in variables like ellipseX, ellipseY, and ellipseSize.
    2. You could create a class that stores the values you want. Shameless self-promotion: here is a tutorial on creating classes in p5.js.
    3. You could draw the ellipse to a p5.Graphics and then store that p5.Graphics in a global variable. You can find more info about this in the reference.