views:

1148

answers:

2

I'm trying to figure out how to rotate a single object on an html 5 canvas.

For example: http://screencast.com/t/NTQ5M2E3Mzct - I want each one of those cards to be rotated at a different degree.

So far, all I've seen are articles and examples that demonstrate ways to rotate the entire canvas. Right now, I'm guessing I'll have to rotate the canvas, draw an image, and then rotate the canvas back to it's original position before drawing the second image. If that's the case, then just let me know! I just have a feeling that there's another way.

Anyone have any idea?

Thanks in advance!

+3  A: 

Unfortunately in the HTML5 canvas element you can't rotate individual elements.

Animation works like drawing in MS Paint: You draw something, make a screen.. use the eraser to remove some stuff, draw something differently, make a screen.. Draw something else on top, make a screen.. etc etc.

If you have an existing item on the canvas - you'll have to erase it ( use ctx.fillRect() for example ), and then draw the rotated object.

If you're not sure how to rotate it while drawing in the first place:

ctx.save();
ctx.rotate(0.17);
// draw your object
ctx.restore();
Artiom Chilaru
Bummer! I guess that'll have to do, Artiom! Thanks for the response!
Kappers
Yeah, I know.. when writing more complex animations this issue becomes even bigger, because you have to redraw the whole canvas from scratch with each frame :)
Artiom Chilaru
A: 

Artion is right - As per the HTML5 Canvas spec

There is only one CanvasRenderingContext2D object per canvas, so calling the getContext() method with the 2d argument a second time must return the same object.

rotate is a function of context and can only be done on the one and only 2d context for that canvas canvas.

Romain Hippeau