michael
michael

Reputation: 33

Animation in this canvas game only works once

I’m trying to create a simple canvas game:

I have this code on CodePen

var canvas;
var ctx;
var x = 300;
var y = 400;
var r = 0;
var mx = 0;
var my = 0;
var WIDTH = 600;
var HEIGHT = 400;


function circle(x,y,r) {
  ctx.fillStyle = "blue";
  ctx.beginPath();
  var text = Math.floor(Math.random()*10000);
  var font = "bold " + (r*0.75) +"px serif";
  var textWidth = ctx.measureText(text).width;
  var textHeight = ctx.measureText("w").width;
  ctx.arc(x, y, r, 0, Math.PI*2, true);
  ctx.fill();
  ctx.moveTo(50, 0);
  ctx.lineTo(50, 10);
  ctx.stroke();
  ctx.moveTo(100, 0);
  ctx.lineTo(100, 10);
  ctx.stroke();
  ctx.moveTo(150, 0);
  ctx.lineTo(150, 10);
  ctx.stroke();
  ctx.fillStyle = "black"; // font color to write the text with
  ctx.font = font;
  ctx.fillText(text, x - (textWidth/2), y + (textHeight/2));
  ctx.strokeStyle = '#000';  
  ctx.stroke();
}
 
function clear() {
  ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
 
function init() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  return setInterval(draw, 10);
}
 
function draw() {
  clear();
  circle(x, y, r);

  if (y>=350){
      y=y-0.5;
      r=r+0.3;
  }
  if (y<=350){
      y=y-1;
      x=x-0.75;
  }
  if (y<=50){
      x=x+0.75;
      r=r-0.2;
  }
}
<canvas id="canvas" width="600" height="400"></canvas>
<button id="test" onclick="return init()">test</button>

By pressing the button you release bubbles and it has numbers rolling inside.

My questions are

  1. How can I make the numbers stop at some point? I use random function for text value.

  2. My button to launch bubbles only works once, I use setInterval to start the animation. What I want is to launch another bubble, and the previous bubbles would still continue the animation until they disappear.

Upvotes: 3

Views: 112

Answers (1)

DUUUDE123
DUUUDE123

Reputation: 166

  1. Don't return setInterval in the init function
  2. call your init function when the window has loaded using window.addEventListener("load", init);
  3. Use window.requestAnimationFrame for animations

Hope this helps :)

Upvotes: 1

Related Questions