问题描述
如何使用画布的旋转功能围绕图片中心旋转图片,而不是绕原点旋转。
请注意以下示例: < html>
< head>< / head>
< body>
< canvas id =tmpstyle =width:300px; height:300px; border:1px red solid/>
< script type =text / javascript>
var deg = 0;
function Draw(){
var ctx = document.getElementById('tmp')。getContext('2d');
ctx.save();
ctx.fillStyle =white;
ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.fillStyle =red;
ctx.rotate(deg * 0.0174532925199432957) // Convert to rad's
ctx.fillRect(50,50,20,20);
ctx.restore();
deg + = 5;
setTimeout(Draw(),50);
}
Draw();
< / script>
< / body>
< / html>
在这个例子中,红色方块围绕orgin在0,0处旋转。说我想绕中心旋转正方形。我试图使用翻译移动到原点,然后旋转,然后再次使用翻译移动它如此:
ctx.translate( - (50 + 10), - (50 + 10)); // Move to origin
ctx.rotate(deg * 0.0174532925199432957); // rotate
ctx.translate(50,50); // move back to original location
ctx.fillRect(50,50,20,20);
ctx.restore();
但是它看起来像对translate函数的调用重写了以前的translate并且不结合转换。
这是你正在寻找什么:?
//移动到矩形的中心
ctx.translate(60,60);
ctx.rotate(deg * 0.0174532925199432957); // rotate
//绘制矩形
ctx.fillRect(-10,-10,20,20);
ctx.restore();
请注意,您应该使用 Math.PI / 180
而不是那个大的十进制。
我还设置了 width
和 height
画布,并将 setTimeout
更改为不使用 eval()
。
How do I rotate an image using the canvas's "rotate" function around the center of the image instead of rotating around the origin point.
Consider the following example:
<html>
<head></head>
<body>
<canvas id="tmp" style="width: 300px; height: 300px; border: 1px red solid" />
<script type="text/javascript">
var deg = 0;
function Draw() {
var ctx = document.getElementById('tmp').getContext('2d');
ctx.save();
ctx.fillStyle = "white";
ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.fillStyle = "red";
ctx.rotate(deg * 0.0174532925199432957); //Convert to rad's
ctx.fillRect(50, 50, 20, 20);
ctx.restore();
deg+=5;
setTimeout("Draw()", 50);
}
Draw();
</script>
</body>
</html>
in this example the red square is rotated around the orgin at 0,0. Say I wanted to rotate the square around its center. I've tried to use translate to move it to the origin then rotate then use translate again to move it back like so:
ctx.translate(-(50 + 10), -(50 + 10)); //Move to origin
ctx.rotate(deg * 0.0174532925199432957); //rotate
ctx.translate(50, 50); //move back to original location
ctx.fillRect(50, 50, 20, 20);
ctx.restore();
But it looks like calls to the translate function override the previous translate and don't combine the transformations. How then do I attain the effect I want?
Is this what are you are looking for: jsFiddle?
//Move to center of rectangle
ctx.translate(60, 60);
ctx.rotate(deg * 0.0174532925199432957); //rotate
//Draw rectangle
ctx.fillRect(-10, -10, 20, 20);
ctx.restore();
Note that you should use Math.PI/180
instead of that large decimal.
I also set your width
and height
properly on the canvas, and changed your setTimeout
to not use eval()
.
这篇关于HTML5用画布旋转图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!