gpt4 book ai didi

javascript - 用与图像中心点相关的 x,y 绘制图像?

转载 作者:太空宇宙 更新时间:2023-11-04 15:28:57 25 4
gpt4 key购买 nike

我试图在坐标点 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));
}

然而,它似乎在下方和右侧绘制图像?即 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));
}

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

关于javascript - 用与图像中心点相关的 x,y 绘制图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16545909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com