5
votes

Are nested animations possible using canvas and javascript? For example, a butterfly flapping its wings whilst simultaneously moving along a path.

What would be the best way of going about creating this kind of animation? There will be multiple instances of the same butterfly moving in different directions.

At the minute I'm drawing the butterfly shape on the canvas, in two parts, the left and right wings, which I will animate separately. Then I'll go abou animating the whole butterfly on a path.

It just seems like there will be a lot of processing used on the multiple drawings and animations, could this be saved by using a PNG rather than a shape, or even an animated GIF?

Any advice would be appreciated! Thanks!

1

1 Answers

6
votes

To answer your first question: yes, they are possible. To answer your second question: one 'best' way would be to use the arbitrary nesting of transformations on the canvas context.

I've created an example showing how you can issue drawing commands on the context with no idea what your current transformation is, and then wrap those commands in transformations that animate the result.

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

Here's 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's 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();
}