我正在尝试在 HTML5 Canvas 上操作一个简单的矩形。执行此操作的 Javascript 在这里:
var canvas = document.getElementById("mainCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, windowWidth, windowHeight);
var halfWidth = (iconWidth / 2);
var halfHeight = (iconHeight / 2);
var centreX = x + halfWidth;
var centreY = y + halfHeight;
ctx.fillStyle = "#FF0000";
ctx.translate(centreX, centreY);
ctx.rotate(rotationDegree * Math.PI / 180);
ctx.fillRect(-halfWidth, -halfHeight, iconWidth, iconHeight);
ctx.translate(-centreX, -centreY);
当我增加 y
时,我可以看到矩形在屏幕上移动,如果我旋转矩形,它会旋转并沿着新的轨迹移动;然而,为了阻止矩形离开屏幕,我进行了基本的边界检查,但它不起作用(矩形移出屏幕,并在未到达边缘的地方被“弹回”。
作为实验,我尝试了以下操作:
var canvas = document.getElementById("mainCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, windowWidth, windowHeight);
var halfWidth = (iconWidth / 2);
var halfHeight = (iconHeight / 2);
var centreX = x + halfWidth;
var centreY = y + halfHeight;
ctx.save();
ctx.fillStyle = "#FF0000";
ctx.translate(centreX, centreY);
ctx.rotate(rotationDegree * Math.PI / 180);
ctx.fillRect(-halfWidth, -halfHeight, iconWidth, iconHeight);
// ctx.translate(-centreX, -centreY);
ctx.restore();
这可行,但旋转不再引导矩形。我的结论是 rotate 函数旋转 Canvas ,但随后以新的旋转形式保留它(就像在笔下旋转一张纸)。所以,我遇到的错误是旋转没有被重置;然而,除了边界检查之外,这种“有问题的”行为才是我真正想要的。
有没有办法从 Canvas 2d 上下文获取绝对位置,同时考虑到旋转,这样即使我将 Canvas 保持在“旋转”状态,我也可以执行边界检查?
最佳答案
要将一个点从本地空间(转换后的空间)转换到屏幕空间,创建一个矩阵,该矩阵是上下文转换的阴影(副本),然后将该点与该矩阵相乘
function getTransformToScreen(x,y,rotation,posX,posY){
var xAx = Math.cos(rotation); // x axis x
var xAy = Math.sin(rotation); // x axis y
// the equivalent to
// ctx setTransform(xAx, xAy ,-xAy, xAx, posX, posY);
// second two values (y Axis) is at 90 deg of x Axis if it is
// not at 90 (skewed) then you need to calculate the skewed axis (y axis) direction
return {
x : x * xAx - y * xAy + posX,
y : x * xAy + y * xAx + posY
}
}
使用
// your code
ctx.translate(centreX, centreY);
ctx.rotate(rotationDegree * Math.PI / 180);
ctx.fillRect(-halfWidth, -halfHeight, iconWidth, iconHeight);
// get the top left
var topLeft = getTransformToScreen(
-halfWidth, -halfHeight,
rotationDegree * Math.PI / 180,
centreX, centreY
);
关于javascript - HTML5 捕捉旋转和平移后的绝对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43615280/