2

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?

4

3 回答 3

3

在该方法的开始,它将上下文从左上角转换到中心。如果你想通过图像的中心。然后您可以跳过该步骤,从而生成以下代码。

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));
}

不要忘记您必须以与更改翻译相同的方式撤消翻译。

于 2013-05-14T14:36:20.380 回答
1

如果你想给这个函数中心坐标而不是左上角,只需替换

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

context.translate(x, y);
于 2013-05-14T14:36:48.657 回答
1

聚会有点晚了,但我发现在渲染之前移动图像最容易。

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

如您所知,当它通过时的宽度和高度,您可以将图像向上移动一半大小,向左移动一半大小。快速而肮脏,但可以解决问题。

于 2016-11-21T06:48:23.793 回答