Mik*_*ike 5 html javascript html5 canvas
如何使用画布围绕图像中心的"旋转"功能旋转图像,而不是围绕原点旋转.
请考虑以下示例:
<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>
Run Code Online (Sandbox Code Playgroud)
在这个例子中,红色方块围绕orgin旋转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();
Run Code Online (Sandbox Code Playgroud)
但看起来对translate函数的调用会覆盖先前的translate并且不会组合转换.那怎么能达到我想要的效果呢?
这是你在寻找什么: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();
Run Code Online (Sandbox Code Playgroud)
请注意,您应该使用Math.PI/180而不是那个大小数.
我还设置你的width和height正确的画布上,并变更setTimeout为不使用eval().