Eclissi
Eclissi

Reputation: 35

Stuck with canvas/JS animation

I'm working on a game to play in canvas, and was wanting to add some ambiance to a background layer using javascript. To start, here is the code...

  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext("2d");
  var x = canvas.width/2;
  var y = canvas.height-150;
  var dx = Math.random() * (-5 * 5) + 15;
  var dy = -15;

  function drawDot() {
      ctx.beginPath();
      ctx.arc(x, y, 10, 0, Math.PI*2);
      ctx.fillStyle = "black";
      ctx.fill();
      ctx.closePath();
  };

  function move() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      drawDot();
      x += dx;
      y += dy;
  };
setInterval(move, 50);

If you run that, you can see that what I have is a black ball that moves up and off the page inside a random conal space. What I need help with is figuring out the best way to:
A. Populate it with more balls (maybe like 2-3) that are on their own random trajectory, and
B. Make it so those 2-3 balls are constantly animating inside the random cone area off the page from the same starting area (kind of like a constant spurting fountain effect).

A problem I can already see is that by using the console log, the 1 working ball I have now just keeps going off into infinity outside the canvas, so when I try to add a new one it won't run the function. I'm very new to javascript and especially canvas so apologies if this is obvious! Thank you for any help with this!

Upvotes: 0

Views: 183

Answers (1)

Emil S. Jørgensen
Emil S. Jørgensen

Reputation: 6366

There is a good tutorial by Seb Lee-Delisle on this exact problem here:

https://vimeo.com/36278748

Basically you have to encapsulate each Dot so it knows about its own position and acceleration.

EDIT 1

Here is an example using you own code:

document.body.innerHTML = '<canvas height="600" width="600" id="myCanvas"></canvas>';
clearInterval(interval);
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var dotArray = [];

function Dot() {
    var dot = {
        y : canvas.height / 2,
        x : canvas.width / 2,
        speedX : Math.random() * ( - 5 * 5) + 15,
        speedY : Math.random() * ( - 5 * 5) + 15,
        age : 0,
        draw : function () {

            this.x += this.speedX;
            this.y += this.speedY;

            ctx.beginPath();
            ctx.arc(this.x, this.y, 10, 0, Math.PI * 2);
            ctx.fillStyle = 'black';
            ctx.fill();
            ctx.closePath();
        }
    };
    return dot;
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for (var i = 0; i < dotArray.length; i++) {
        dotArray[i].draw();
        dotArray[i].age++;
        if (dotArray[i].age > 20) {
            dotArray.splice(i, 1);
        }
    }
    dotArray.push(new Dot());
}

draw();
var interval = setInterval(draw, 1000 / 60);

Upvotes: 1

Related Questions