dan2k3k4 dan2k3k4 - 18 days ago 5
Javascript Question

Draw image with x,y relating to the center point for the image?

I'm trying to draw an image at co-ordinate points x,y with x and y being in the center of the image.

I have this code that I found earlier for rotating an image:

function drawImageRot(img,x,y,width,height,deg) {
//Convert degrees to radian
var rad = deg * Math.PI / 180;

//Set the origin to the center of the image
context.translate(x + width / 2, y + height / 2);

//Rotate the canvas around the origin
context.rotate(rad);

//draw the image
context.drawImage(img, width / 2 * (-1), height / 2 * (-1), width, height);

//reset the canvas
context.rotate(rad * ( -1 ) );
context.translate((x + width / 2) * (-1), (y + height / 2) * (-1));
}


However it seems to draw the image below and to the right? i.e. the x,y co-ordinates relate to the top left corner of the image?

Answer

At the beginning of that method it translates the context from the top-left to the center. If you want to pass in the center of the image. Then you can skip that step, resulting in the following code.

function drawImageRot(img,x,y,width,height,deg) {
  //Convert degrees to radian
  var rad = deg * Math.PI / 180;


  //Set the origin to the center of the image
  context.translate(x, y);

  //Rotate the canvas around the origin
  context.rotate(rad);

  //draw the image
  context.drawImage(img, width / 2 * (-1), height / 2 * (-1), width, height);

  //reset the canvas
  context.rotate(rad * ( -1 ) );

  //
  context.translate((x) * (-1), (y) * (-1));
}

Don't forget that you have to undo the translation in the same manner that you change the translation.