dan2k3k4
dan2k3k4

Reputation: 1419

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?

Upvotes: 2

Views: 7105

Answers (3)

Plentybinary
Plentybinary

Reputation: 179

Little late to the party but i find it easiest to shift the image before you render it.

function drawBorder(img, x, y, width, height, deg){
    var xAdjust = width * .5,
        yAdjust = height * .5;
    ctx.drawImage(img, x - xAdjust, y - yAdjust, width, height);
}

As you know the width and height when its passed you can just move the image up half of its size and left half of its size. Quick and dirty but does the trick.

Upvotes: 1

igor
igor

Reputation: 2926

If you want to give this function coordinates of center instead of left top corner, just replace

context.translate(x + width / 2, y + height / 2); 

with

context.translate(x, y);

Upvotes: 1

Lee Louviere
Lee Louviere

Reputation: 5262

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.

Upvotes: 3

Related Questions