Canvas object not changing X position?

1182 views javascript
0

I'm trying to change the X position of an object by 1 on every draw(). However, the ellipse is not moving, and I'm not getting any errors.

function setup() {
    createCanvas(windowWidth, windowHeight - 4);
}

function windowResized() {
    resizeCanvas(windowWidth, windowHeight - 4);
}

function draw() {
    background(51, 51, 51);

    var el1 = {
        x: 100,
        y: 100,
        width: 50,
        height: 50
    };

    var el2 = {
        x: 300,
        y: 300,
        width: 50,
        height: 50
    };

    ellipse(el1.x, el1.y, el1.width, el1.height);
    ellipse(el2.x, el2.y, el2.width, el2.height);
    el1.x = el1.x + 1;

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.js"></script>

answered question

1 Answer

10

You're recreating the el1 and el2 variables every frame, so you're restarting them at their default values.

If you want to modify a single el1 variable, then you need to declare it at the top of your sketch.

Compare this code:

function draw(){
  var x = 42;
  console.log(x); // always prints 42
  x = x + 1;
}

To this code:

var x = 42;

function draw(){
  console.log(x);
  x = x + 1;
}

posted this

Have an answer?

JD

Please login first before posting an answer.