开发者

Canvas Animation

I'm making a graph script using canvas, i'm adding animation to a chart but i don't like the w开发者_Python百科ay that it's look, i use setInterval for X function adding height to a rectangle to make a bar chart for example, but i wanna an animation more fluid, is another way to do an animation?


no no no. There are three ways to create an animation with JS:

  1. setTimeout()
  2. setInterval()
  3. requestAnimationFrame

options #1 and #2 are old-school ways of creating animations. option #3 is a newer spec and yields the smoothest animations because the browser itself is dynamically controlling the FPS. Here's an awesome shim created by Paul Irish that creates a requestAnimFrame wrapper to handle all browser implementations:

// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame    || 
          window.oRequestAnimationFrame      || 
          window.msRequestAnimationFrame     || 
          function(/* function */ callback, /* DOMElement */ element){
            window.setTimeout(callback, 1000 / 60);
          };
})();


// usage: 
// instead of setInterval(render, 16) ....

(function animloop(){
  render();
  requestAnimFrame(animloop, element);
})();


I'm assuming that you have rectangles of initial height 0, and you're increasing height per interval until you reach a set point... and that you want to make the animation "smoother"?

To make it more fluid, you just lower the 2nd parameter of setInterval [delay] so that the first parameter [function to call] is called more...

In addition, you can add a tween with a slowdown at the end by using the formula
rect.h = (rect.h*N+targetHeight)/(N+1)... where N > 1...
So that initially, the bar grows by a lot and then eventually slows down growth to the target height.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜