How to rotate one image in a canvas?
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()
}
Look at my solution. It's full example and the easiest to understand.
var drawRotate = (clockwise) => {
const degrees = clockwise == true? 90: -90;
let canvas = $('<canvas />')[0];
let img = $(".img-view")[0];
const iw = img.naturalWidth;
const ih = img.naturalHeight;
canvas.width = ih;
canvas.height = iw;
let ctx = canvas.getContext('2d');
if(clockwise){
ctx.translate(ih, 0);
} else {
ctx.translate(0, iw);
}
ctx.rotate(degrees*Math.PI/180);
ctx.drawImage(img, 0, 0);
let rotated = canvas.toDataURL();
img.src = rotated;
}
Your original "solution" was:
ctx.save();
ctx.translate(x,y);
ctx.rotate(-this.angle + Math.PI/2.0);
ctx.translate(-x, -y);
ctx.drawImage(this.daggerImage,x,y,20,20);
ctx.restore();
However, it can be made more efficient (with no save
or restore
) by using this code:
ctx.translate(x,y);
ctx.rotate(-this.angle + Math.PI/2.0);
ctx.drawImage(this.daggerImage,x,y,20,20);
ctx.rotate(this.angle - Math.PI/2.0);
ctx.translate(-x, -y);
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)
}