lundi 20 janvier 2020

How to randomly duplicate objects on a canvas

I made a fireworks in canvas. I want to duplicate this to a random location inside the canvas.

Finally, I want to run in random order from random locations. What more should I add?

var ctx = document.getElementById('canvas').getContext('2d');

ctx.translate(100, 100);

function fireworks() {
  //clipping
  ctx.beginPath();
  ctx.arc(0, 0, 60, 0, Math.PI * 2, true);
  ctx.clip();

  var x = 130; //final position
  var t = 0; //0-1, this is what you change in animation loop
  var tx = 0; //actual position of element for x

  function myLoop() {
    ctx.clearRect(-(canvas.width / 2), -(canvas.height / 2), canvas.width, canvas.height);
    tx = EasingFunctions.easeInOutQuad(t) * x;
    for (var i = 0; i < 12; i++) {
      ctx.beginPath();
      ctx.rotate(Math.PI / 6);
      ctx.arc(tx, tx, 5, 0, Math.PI * 2);
      ctx.fill();
      ctx.closePath();
    }

    if (t < 1) {
      t += 0.01; //determines speed
      requestAnimationFrame(myLoop);
    }
  }
  myLoop();
}
EasingFunctions = {
  easeInOutQuad: function(t) {
    return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t
  }
}


fireworks();
#canvas {
  border: 1px solid #000;
}
<canvas id="canvas" width="800" height="600"></canvas>



Aucun commentaire:

Enregistrer un commentaire