来看看神奇的消失矩形!
但说真的,我有一个非常简单的 HTML5 Canvas ,它只绘制一个矩形(使用 lineTo 而不是 rect 出于某种原因)。
我的问题:我试图将矩形旋转 90 度。该矩形应旋转 90 度,但它却消失了。
在我的 webapp 项目中,当我在 HTML5 canvas 中旋转我的复杂多边形时出现奇怪的 x,y 放置错误,因此我创建了这个简单的 HTML 来测试旋转并确保它围绕其 x,y 点 100,100 旋转。但是,当我尝试旋转形状时,即使这样也会产生奇怪的结果。
谁能告诉我如何让我的矩形可见,以及如何在不完全改变 x、y 值的情况下围绕特定点旋转多边形。
有没有人遇到过 HTML5 canvas 的这个问题并且知道解决这个问题的方法?
<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);
关于javascript - 围绕任意点旋转 : HTML5 Canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8936803/