Javascript 使用与图像中心点相关的x、y绘制图像?

Javascript 使用与图像中心点相关的x、y绘制图像?,javascript,html,canvas,Javascript,Html,Canvas,我试图在坐标点x,y处画一幅图像,x和y在图像的中心 我在前面找到了用于旋转图像的代码: 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

我试图在坐标点x,y处画一幅图像,x和y在图像的中心

我在前面找到了用于旋转图像的代码:

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

然而,它似乎画了下面和右边的图像?i、 e.x,y坐标与图像的左上角有关?

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

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

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

在该方法的开头,它将上下文从左上角翻译到中间。 如果要在图像的中心通过。然后可以跳过该步骤,生成以下代码

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

不要忘记,您必须以更改平移的相同方式撤消平移。

如果您要为该函数指定中心坐标而不是左上角坐标,只需替换即可

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


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

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


派对有点晚了,但我发现在渲染之前移动图像是最容易的

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

正如您所知道的,当图像经过时,您可以将图像向上移动一半大小,向左移动一半大小。又快又脏,但效果很好。

派对有点晚了,但我发现在渲染之前移动图像是最容易的

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

正如您所知道的,当图像经过时,您可以将图像向上移动一半大小,向左移动一半大小。又快又脏,但很管用。

是的。在大多数框架中,(0,0)坐标是容器的左上角。这对于图像和表单中的控件都是如此。我添加了几个标记以获得更高的可见性-如果我猜错了,请更正!对在大多数框架中,(0,0)坐标是容器的左上角。这对于图像和表单中的控件都是如此。我添加了几个标记以获得更高的可见性-如果我猜错了,请更正!如果您的意思是不需要旋转,那么您也可以删除这两个rotate语句。如果您的意思是不需要旋转,那么您也可以删除这两个rotate语句。