Animation

Next ❯Advance

To create animation onto the canvas

  • turned_in_notAnimation Related Methods
    • requestAnimationFrame()
    • cancelAnimationFrame()


requestAnimationFrame( )

Used to start animation

Syntax

requestAnimationFrame(function)

cancelAnimationFrame( )

Used to cancel the animation created using requestAnimationFrame()

Syntax

cancelAnimationFrame(requestAnimationVariable)

MouseOver on the canvas to start animation & MouseOut to stop animation
<canvas id="canvas" width="200" height="100" style="border:1px solid teal;"></canvas>

<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var speed=3,y=50,animation;

function draw() {
  ctx.clearRect(0,0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(100, y, 15, 0, Math.PI * 2, true);
  ctx.stroke();
  y+=speed;
  if (y+speed > canvas.height || y+speed <25) speed = -speed;
  animation = requestAnimationFrame(draw);
}

canvas.addEventListener('mouseover', function() {
  animation = requestAnimationFrame(draw);
});

canvas.addEventListener('mouseout', function() {
  cancelAnimationFrame(animation);
});
</script>
Animation


  • Advance
❮ Prev Save & Restore
Next ❯Advance
TryOut Examples"Learn to Explore..!"

TryOut Editor

receipt