Search code examples
javascriptanimationhtmlcanvas

How do I rotate a single object on an html 5 canvas?


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?


Solution

  • 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() or clearRect() 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();