围绕任意点旋转:HTML5画布
Rotating around an arbitrary point: HTML5 Canvas
来看看令人惊叹的消失矩形吧!
但说真的,我有一个非常简单的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>
相关文章:
- JavaScript HTML5画布未显示
- html5画布动画无法正常工作
- 在HTML5画布上添加按钮和控件
- 如何在运行时在HTML5画布中绘制正方形
- Unicode字符未在HTML5画布中正确呈现
- 鼠标点击HTML5画布绘制矩形
- html5画布在同一行中写入多个字体
- HTML5画布-暂停时的运行时间
- 使用JavaScript和HTML5画布进行冲突检测
- 什么是HTML5画布标记的回退
- 如何在html5画布中绘制圆形作为单独的画布
- 如何在flash html5画布项目中动态更改文本颜色
- HTML5画布支持和Android Webview
- html5画布中的套索工具
- 什么'是在HTML5画布中创建关键事件的最佳方式
- Javascript:延迟在html5画布上循环绘制
- 如何在HTML5画布上呈现音频波形
- HTML5画布动画滑块
- 如何将 html5 画布另存为窗口 8 Metro 应用程序中的图像文件
- HTML5-画布元素&自定义光标