Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate one image in a canvas?

I am making an HTML5 canvas game, and I wish to rotate one of the images.

var link = new Image();
link.src='img/link.png';
link.onload=function(){
    ctx.drawImage(link,x,y,20,20); // draws a chain link or dagger
}

I wish to rotate this image. The standard way of rotating image was to set a rotation on the canvas context object. However, that rotates the entire game! I don't want to do that, and only wish to rotate this one sprite. How do I do that?

like image 432
Razor Storm Avatar asked Sep 21 '11 08:09

Razor Storm


People also ask

Can you rotate an image in canvas?

If you'd like to see the controls only when the canvas is rotated, choose Automatically Show Controls. To rotate canvas at increments of 15°, press and hold the Shift ⇧ key while rotating.


2 Answers

Use .save() and .restore() (more information):

link.onload=function(){
    ctx.save(); // save current state
    ctx.rotate(Math.PI); // rotate
    ctx.drawImage(link,x,y,20,20); // draws a chain link or dagger
    ctx.restore(); // restore original states (no rotation etc)
}
like image 68
pimvdb Avatar answered Sep 23 '22 09:09

pimvdb


You might want to put a translate(); there because the image is going to rotate around the origin and that is in the top left corner by default so you use the translate(); to change the origin.

link.onload=function(){
    ctx.save();
    ctx.translate(x, y); // change origin
    ctx.rotate(Math.PI);
    ctx.drawImage(link,-10,-10,10,10);
    ctx.restore()
}
like image 23
Carb0n1c Avatar answered Sep 23 '22 09:09

Carb0n1c