Rotate the image to its center in the canvas

I have a strange problem, when I make a rotation that goes through the value of the literal angle (I get the previous angle printed by the console and put a variable instead), it works fine, but if I run the code that passes the variable, like my code below, the image drawn "more on top and left" (sorry for my poor english)

function setImg(src,x,y,angle) { var TO_RADIANS = Math.PI/180; var base_image = new Image(); base_image.src = src base_image.onload = function () { console.log("-->->"+parseFloat(angle)) ctx.save(); //saves the state of canvas ctx.translate(x+(base_image.width/2), y+(base_image.height/2)); //let translate ctx.rotate(angle*TO_RADIANS); //increment the angle and rotate the image ctx.drawImage(base_image, -(base_image.width/2),-(base_image.height/2)); //draw the image ;) ctx.restore(); //restore the state of canvas }; } 

thanks!

+6
source share
1 answer

The functions ctx.transform , ctx.rotate , ctx.scale and ctx.translate work by creating a new matrix and then multiplying the existing transformation by this new matrix.

This means that the result of using these functions will depend on the current state of the conversion.

To ensure that the transforms are applied to the default matrix (identifier) ​​reset the transform matrix with the ctx.setTransform(1, 0, 0, 1, 0, 0) function, which replaces the existing matrix with the new default matrix.

If you do this before each set of transforms, you will not need to use save and restore to maintain the current state of the transform.

+4
source

All Articles