5
如何使用画布的“旋转”功能围绕图像中心旋转图像,而不是围绕原点旋转。HTML5使用画布旋转图像
考虑下面的例子:在这个例子中,红色正方形是在0,0围绕渊源考旋转
<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>
。假设我想围绕其中心旋转方块。我试图用翻译将其移动到原点,然后旋转,然后再次使用翻译将其移回像这样:
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函数覆盖以前的翻译并没有结合转换。那么我怎样才能达到我想要的效果呢?