Nested animations using canvas and javascript

Can nested animations use canvas and javascript? For example, a butterfly flaps its wings while moving along a path.

What would be the best way to create such an animation? There will be several instances of the same butterfly, moving in different directions.

At that moment, when I draw the shape of a butterfly on canvas, in two parts - the left and right wings, which I will animate separately. Then I will go, animating the whole butterfly on the way.

It looks like there will be a lot of processing used on several drawings and animations, can this be saved using PNG, not a form or even an animated GIF?

Any advice would be appreciated! Thank!

+5
source share
1 answer

To answer your first question: yes, they are possible. To answer your second question: the “best” way would be to use an arbitrary transform nesting in the context of the canvas.

I created an example showing how you can issue drawing commands in a context without knowing what your current transformation is, and then wrap these commands in transforms that enliven the result.

See the result here: http://phrogz.net/tmp/canvas_nested_animations.html

Here is a basic overview of the approach:

// Draw a bug with animated legs
function drawBug(){
  ctx.save();
  // Issue drawing commands, assuming some 0,0 center and an unrotated bug
  // Use the current time, or some frame counter, to change how things are drawn
  ctx.restore();
}

// Move the (animated) bug around
function drawMovingBug(){
  ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);

  ctx.save();
  // Adjust the bug location/rotation based on some animation path
  // and the current time or frame counter.
  var bugPosition = findCurrentBugPosition();
  ctx.rotate(bugPosition.angle);
  ctx.translate(bugPosition.x,bugPosition.y);

  // Draw the bug using the new transformation
  drawBug();          
  ctx.restore();
}
+6
source

All Articles