I want to animate an html5 canvas element with just a simple shape drawn using the path mechanism. When hovering a mouse over it I want to zoom in on it, make it more opaque and change the colors. Can I do this with jQuery's animate() function? What's the best approach? Does canvas have a mechanism to do this kind of animation?
Unfortunately what you want to do would be very difficult using canvas (no longer the case - see UPDATE below) because once you draw a path on canvas it's just pixels so you can't just attach event handlers to it like with the DOM.
Fortunately you can do it if instead of canvas you use SVG because all of the shapes in SVG are DOM nodes just like divs and spans in HTML.
Unfortunately, SVG is not supported on IE.
Fortunately on IE you can use VML instead of SVG.
Unfortunately you can't use jQuery to animate SVG and VML objects easily.
Fortunately there's Raphaël, a JavaScript library with API heavily inspired by jQuery that does it all for you. It uses VML on IE and SVG on other bowsers. It works on Firefox 3.0+, Safari 3.0+, Chrome 5.0+, Opera 9.5+ and Internet Explorer 6.0+.
This is how you would make a red circle that would slowly change color to yellow on mouse over:
// make a Raphael "paper" similarly to an HTML5 canvas:
var paper = Raphael(10, 10, 320, 240);
// make a circle on this paper:
var circle = paper.circle(100, 80, 20);
// change some attributes:
circle.attr({
fill: 'red'
});
// register mouse enter and mouse leave event handlers:
circle.hover(
function() {
circle.animate({
fill: 'yellow'
}, 300);
},
function() {
circle.animate({
fill: 'red'
}, 300);
}
);
And that's it – see DEMO.
See this more complicated DEMO that makes a circle and on mouse hover does exactly what you asked about – zoom in on it, make it more opaque and change the colors.
See also this demo that I wrote for this answer about Raphaël.
When I originally posted this answer I wrote that what you are asking for would be very difficult to do using canvas because you would have to maintain some object hierarchy that is not present in canvas like it is in SVG or VML. It is still true but now there are libraries that can do the "very difficult" part for you, like for example EaselJS, KineticJS, Paper.js or Fabric.js and some others (see this comparison of canvas libraries maintained by the author of Fabric.js for more).
well on this page google used some animated canvas icons. http://www.google.com/chromeos/features.html
when you dig into code you'll see that they used JS Tweener. http://coderepos.org/share/wiki/JSTweener
i think its more reliable than raphaelJS if google chooses it ;). Canvas animation code is really complex though. i barely understand whats happening.
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