围绕任意点旋转:HTML5 Canvas [英] Rotating around an arbitrary point: HTML5 Canvas

查看:254
本文介绍了围绕任意点旋转:HTML5 Canvas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来看看惊人的消失的矩形!

Come see the amazing disappearing rectangle!

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

But seriously I have a really simple HTML5 canvas that just draws a rectangle(using lineTo instead of rect for a reason).

我的问题:我试图将矩形旋转90度。

My Problem: I am attempting to rotate the rectangle 90 degrees. The rectangle should be rotated 90 degrees but instead it disappears.

在我的webapp项目中,当我在HTML5 canvas中旋转我的复杂多边形时,我会得到奇怪的x,y放置错误。 ,所以我创建了这个简单的HTML来测试旋转&确保其围绕其x,y点旋转100,100。但是,当我试图旋转一个形状时,这也有奇怪的结果。

In my webapp project I am getting weird x,y placement errors when I rotate my complex polygons in HTML5 canvas', so I have created this simple HTML to test rotation & ensure its rotating around its x,y point of 100,100. But even this has weird results when I attempt to rotate a shape.

任何人都可以告诉我如何让矩形可见,如何旋转我的多边形围绕一个特定的点,没有他们完全改变x,y值。

Can anyone tell me how to get my rectangle visible & how I can rotate my polygons around a specific point without them completely changing x,y values.

有任何人遇到这个问题与HTML5画布'&

Has anyone experienced this issue with HTML5 canvas' & know solutions to fix this?

<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>


推荐答案

要绕点旋转, 。


  • 首先将上下文转换到您要旋转的中心。


像这样:

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);
    dc.rotate( angle*Math.PI/180 ); 
    dc.translate(-150,-200);

    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);

这篇关于围绕任意点旋转:HTML5 Canvas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆