【发布时间】:2011-08-19 14:50:16
【问题描述】:
如何使用画布的“旋转”功能围绕图像中心旋转图像,而不是围绕原点旋转。
考虑以下示例:
<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>
在本例中,红色方块在 0,0 处围绕原点旋转。假设我想围绕它的中心旋转正方形。我尝试使用 translate 将其移动到原点然后旋转,然后再次使用 translate 将其移回,如下所示:
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 并且不组合转换。那怎样才能达到我想要的效果呢?
【问题讨论】:
标签: javascript html canvas