Animation 4

Beispiel aus dem Kapitel Processing in JavaScript.

Code

var anzahl = 10;
var xpos = [];
var ypos = [];
var xspeed = [];
var yspeed = [];

function setup() {
  let canvas = createCanvas(200, 200);
  canvas.parent('sketch');
  for (let i = 0; i < anzahl; i++) {
    xpos.push(random(10, width-10));
    ypos.push(random(10, height-10));
    xspeed.push(random(-4, 4));
    yspeed.push(random(-4, 4));
  }
}

function draw() {
  background(0);
  for (let i = 0; i < anzahl; i++) {
    ellipse(xpos[i], ypos[i], 20, 20);
    xpos[i] = xpos[i] + xspeed[i];
    ypos[i] = ypos[i] + yspeed[i];
    if (xpos[i] > width-10 || xpos[i] < 10) {
      xspeed[i] = -xspeed[i];
    }
    if (ypos[i] > height-10 || ypos[i] < 10) {
      yspeed[i] = -yspeed[i];
    }
  }
}