Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript HTML5使用画布旋转图像_Javascript_Html_Canvas - Fatal编程技术网

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();