gpt4 book ai didi

javascript - 围绕 Canvas 中的某个点旋转矩形

转载 作者:行者123 更新时间:2023-12-02 18:02:59 27 4
gpt4 key购买 nike

我试图围绕其父矩形的中心旋转一个矩形。 child 到 parent 边界的距离必须始终保持不变。我几乎成功了,但我的方法似乎有一个小错误。我似乎找不到问题所在。

示例:

http://jsfiddle.net/FJ789/3/

我使用以下公式围绕枢轴点旋转。

var rotateAroundPoint = function(point, pivotPoint, sin, cos)
{
position =
{
x : cos * (point.x - pivotPoint.x) - sin * (point.y - pivotPoint.y) + pivotPoint.x
, y : sin * (point.x - pivotPoint.x) + cos * (point.y - pivotPoint.y) + pivotPoint.y
};

return position;
}

最佳答案

在变换(平移和旋转)时不必计算边界框,因为这些变换实际上会旋转整个 Canvas (而不仅仅是新绘制的元素)

这意味着您可以变换 Canvas ,然后正常绘制新元素。

例如,即使在 context.translate 和 context.rotate 之后,此代码也会将父级和子级绘制在相对于彼此相同的位置:

ctx.fillRect(0,0,100,50);   // parent
ctx.fillRect(10,10,30,20); // child

演示:http://jsfiddle.net/m1erickson/WQ4tU/

在每个动画帧中:

  • 清除 Canvas
  • 保存上下文状态
  • 平移到旋转中心点
  • 旋转 Canvas
  • 绘制父子矩形(通过将其 x/y 宽度/高度偏移一半来允许之前的 contect.translate)
  • 将上下文恢复到原始状态(未平移和未旋转)

代码如下:

ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();

// translate to the rotation centerpoint

ctx.translate(150,150);

// rotate

ctx.rotate(radianAngle);

// draw parent rect
// allow for previous ctx.translate by offsetting x/y by half width/height

ctx.fillStyle="green";
ctx.fillRect(-50,-30,100,60);

// draw child rect
// allow for previous ctx.translate by offsetting x/y by half width/height

ctx.fillStyle="red";
ctx.fillRect(-45,-25,30,20);

// restore the original context state

ctx.restore();

关于javascript - 围绕 Canvas 中的某个点旋转矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20353214/

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