Skip to content Skip to sidebar Skip to footer

Canvas Animation Duration In Time

When in HTML canvas we want that the fps will be dynamic and don't let the user device crash we are using requestAnimationFrame() but who I keep the fps of the canvas animation dyn

Solution 1:

The idea is to calculate the amount of milliseconds in between frames, divide it by 1000, then multiply the result with a speed stated in pixels per second.

Here's example code that uses the timing parameter passed to requestAnimationFrame:

var $square;
var x = 0;
var speed = 100; // pixels per secondvar prevTime; // start as undefined to prevent jumpingfunctiontick(now) {
  // schedule next tickrequestAnimationFrame(tick);
  // calculate factor
  delta = (now - prevTime) / 1000;
  prevTime = now;
  if (isNaN(delta)) return; // skip very first delta to prevent jumping

  x += speed * delta;
  $square.css({
    left: x
  });
}

$(document).ready(function () {
  $square = $("#square");
  requestAnimationFrame(tick);
});
body {
  margin: 15px;
  border: 1px solid black;
  width: 500px;
  position: relative;
  line-height: 30px;
}

#square {
  width: 30px;
  height: 30px;
  position: absolute;
  top: 0;
  left: 0;
  background-color: red;
  border-radius: 50%;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
500 pixels in five seconds
<divid="square"></div>

Solution 2:

You should calculate the delta time (time in milliseconds between each frame). This can be done as @Chris G has done. If you want to easely get the delta time between frames and draw a moving object on the canvas, the easiest way would be to use a library such as Canvas.js:

const canvas = newCanvas('my-canvas', 500, 500);

canvas.on('start', function ( ctx, handyObject ) {

  handyObject.Ball = {
    x: 10,
    y: 10,
    speed: 100// Pixels per second
  };
  
});

canvas.on('update', function (handyObject, delta) {

  handyObject.Ball.x += handyObject.Ball.speed * delta; // The magic happens. The speed is multiplied with the delta which often is around 0.016. Delta time is the time since the ball was last updated. Using delta time will make sure the ball moves exactly the same no matter what framerate the client is running.
  
});

canvas.on('draw', function (ctx, handyObject, delta) {

  ctx.clear();

  ctx.beginPath();
  
  ctx.arc(handyObject.Ball.x, handyObject.Ball.y, 10, 0, 2 * Math.PI);
  
  ctx.fill();
  
});

canvas.start();
<scriptsrc="https://gustavgenberg.github.io/handy-front-end/Canvas.js"></script>

Post a Comment for "Canvas Animation Duration In Time"