Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rotate image by its own center in canvas

I have a strange problem, when i do the rotation passing the literal angle value(i get the previous angle printed by console and put instead the variable) it works perfectly but if i run the code passing a variable like my code below, the image is drawn "more top and more left"(sorry for my bad 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's 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!

like image 257
Taborlin El Grande Avatar asked Jan 01 '16 13:01

Taborlin El Grande


1 Answers

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

This means that the result of using these functions will vary depending on the current state of the transformation.

To ensure that the transformations are applied to the default (identity) matrix reset the transformation matrix with the function ctx.setTransform(1, 0, 0, 1, 0, 0) which replaces the existing matrix with the new default matrix.

If you do this before each set of transformations you will not need to use save and restore to keep the current transformation state.

like image 106
Blindman67 Avatar answered Sep 25 '22 10:09

Blindman67