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!
JavaScript animations are done by programming gradual changes in an element's style. The changes are called by a timer. When the timer interval is small, the animation looks continuous.
Since we're using JavaScript to control <canvas> elements, it's also very easy to make (interactive) animations. In this chapter we will take a look at how to do some basic animations. Probably the biggest limitation is, that once a shape gets drawn, it stays that way.
To animate with canvas you need to record the location of your object and then increment it on a new frame setInterval(draw, 1000 / 25); allows you to run a function after a specified time interval. You could use this function to update the position of your object on the page each time a new frame is rendered.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With