围绕任意点旋转:HTML5画布

Rotating around an arbitrary point: HTML5 Canvas

本文关键字:HTML5 画布 旋转 任意点      更新时间:2023-09-26

来看看令人惊叹的消失矩形吧!

但说真的,我有一个非常简单的HTML5画布,它只画一个矩形(使用lineTo而不是rect是有原因的)。

我的问题:我正试图将矩形旋转90度。矩形应该旋转90度,但它却消失了。

在我的webapp项目中,当我在HTML5画布中旋转复杂的多边形时,我会出现奇怪的x,y放置错误,所以我创建了这个简单的HTML来测试旋转;确保其围绕100100的x,y点旋转。但当我试图旋转一个形状时,即使这样也会产生奇怪的结果。

有人能告诉我如何让我的矩形可见吗;如何在不完全改变x,y值的情况下围绕特定点旋转多边形。

有人在HTML5画布上遇到过这个问题吗;知道解决这个问题的方法吗?

<canvas id="testCanvas" width="900px" height="900px" style="background-color: blue;">
</canvas>
<script type="text/javascript">
    var canvas = document.getElementById("testCanvas");
    var dc     = canvas.getContext("2d");
    dc.clearRect(0, 0, canvas.width, canvas.height);
    dc.save();
    dc.fillStyle = "#FF0000";
    dc.rotate( 90*Math.PI/180 );  // rotate 90 degrees
    dc.beginPath();
    dc.moveTo(100, 100);
    dc.lineTo(200, 100);
    dc.lineTo(200,300);
    dc.lineTo(100,300);
    dc.closePath();
    dc.fill();
    dc.restore();
-->
</script>

要围绕一个点旋转,需要执行3个步骤。

  • 首先将上下文转换到要旋转的中心
  • 然后进行实际旋转
  • 然后把上下文翻译回来

像这样:

var canvas = document.getElementById("testCanvas");
var dc     = canvas.getContext("2d");
var angle = 0;
window.setInterval(function(){
    angle = (angle + 1) % 360;
    dc.clearRect(0, 0, canvas.width, canvas.height);
    dc.save();
    dc.fillStyle = "#FF0000";
    dc.translate(150,200); // First translate the context to the center you wish to rotate around.
    dc.rotate( angle*Math.PI/180 ); // Then do the actual rotation.
    dc.translate(-150,-200); // Then translate the context back.
    dc.beginPath();
    dc.moveTo(100, 100);
    dc.lineTo(200, 100);
    dc.lineTo(200,300);
    dc.lineTo(100,300);
    dc.closePath();
    dc.fill();
    dc.restore();
}, 5);

当你旋转画布时,它会从原点(0,0)旋转,所以你的矩形最终会从屏幕上旋转出来。

请参见仅旋转45度的示例:http://jsfiddle.net/wjLSm/

解决这个问题的一种方法是通过画布的宽度&高度/2:http://jsfiddle.net/wjLSm/1/(然后0,0在中间——注意这一点)

你是这样说的吗?

var canvas = document.getElementById("testCanvas");
var dc = canvas.getContext("2d");
dc.clearRect(0, 0, canvas.width, canvas.height);
dc.save();
dc.fillStyle = "#FF0000";
dc.translate(200, -100);
dc.rotate(45 * Math.PI / 180);
dc.beginPath();
dc.moveTo(100, 100);
dc.lineTo(200, 100);
dc.lineTo(200, 300);
dc.lineTo(100, 300);
dc.closePath();
dc.fill();
// rotate 90 degrees
dc.restore();
<canvas id="testCanvas" width="900px" height="900px" style="background-color: blue;">
</canvas>