I'm trying to place an html5 image inside canvas. The image is translated, rotated and scaled using the css transform property. The main problem is how to copy the properties of the image and apply them on the canvas.
You can try the jsfiddle link below: the image can be scaled, moved and rotated and whatever appears in the greenbox should be the same as the one in the red.
https://jsfiddle.net/q7y1py5f/3/. Here I can move and scale the image, but when the rotation kicks in nothing works. Here is the code that bugs me (58 line in the javascript jsfiddle) :
context.save();
context.translate(image.width / 2, image.height / 2);
context.rotate(angle * Math.PI/180);
context.translate(((-image.width) / 2), ((-image.height) / 2));
context.translate(-x, -y);
context.scale(scale, scale);
context.drawImage(image, 0, 0);
context.restore();
Here the x and y are the difference between the top left of the green container and the top left of the image. Any help would be appreciated.
I've managed to get each property to work individually, but when combining them all together it doesn't work. When I only translate and scale the image and apply to the canvas context everything is fine, but when I add the rotation with the image is not where it's supposed to be.
I tried the following - calculated the top-left of the element with the angle to get the right value and then translating and rotating with it.
ctx.rotate()
takes angle in radians as argument. You are passing degrees, you can convert them withMath.PI/180*angle
. Then there is a bigger problem with your translating, not sure right now and I don't have much time to look at it, but I would say you need to get the distance between the original position and the center of your green square. – Kaiido