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?
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.
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)
}
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()
}
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