Javascript HTML5使用画布旋转图像
如何使用画布的“旋转”功能围绕图像中心旋转图像,而不是围绕原点旋转 考虑以下示例:Javascript HTML5使用画布旋转图像,javascript,html,canvas,Javascript,Html,Canvas,如何使用画布的“旋转”功能围绕图像中心旋转图像,而不是围绕原点旋转 考虑以下示例: <html> <head></head> <body> <canvas id="tmp" style="width: 300px; height: 300px; border: 1px red solid" /> <script type="text/javascript">
<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>
但是对translate函数的调用似乎覆盖了前面的translate,并且没有合并转换。那么我怎样才能达到我想要的效果呢?这就是你想要的吗: 请注意,您应该使用
Math.PI/180
而不是那个大小数。我还在画布上正确设置了
宽度
和高度
,并将设置超时
更改为不使用eval()
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();
//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();