6

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!

  • Why not use css to rotate the image? – Mottie Jan 01 '16 at 14:02
  • `base_image` is a global variable. With out the code involved in the declaration and additional use of that var we can not help as there is nothing else wrong with the code. – Blindman67 Jan 01 '16 at 14:14
  • edited: base_image is local variable but still doing the same. I do not use css because i need the images in the canvas to paint over – Taborlin El Grande Jan 01 '16 at 16:07
  • 1
    The only other thing that can happen then is that you have another transformation that is effecting the new transformation you are creating. The functions `ctx.transform`, `ctx.rotate`, `ctx.scale`, and `ctx.translate` work by multiplying the existing transformation. Try reseting the transform to the default with `ctx.setTransform(1,0,0,1,0,0)` just after the `ctx.save` that will fix the problem. – Blindman67 Jan 01 '16 at 16:53

1 Answers1

4

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.

Blindman67
  • 51,134
  • 11
  • 73
  • 136