开发者

HTML5 rotating an image with canvas

开发者 https://www.devze.com 2023-03-29 18:46 出处:网络
How do I rotate an image using the canvas\'s \"rotate\" function around the center of the image instead of rotating around the origin point.

How do I rotate an image using the canvas's "rotate" function around the center of the image instead of rotating around the origin point.

Consider the following example:

<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').getCon开发者_高级运维text('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>

in this example the red square is rotated around the orgin at 0,0. Say I wanted to rotate the square around its center. I've tried to use translate to move it to the origin then rotate then use translate again to move it back like so:

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

But it looks like calls to the translate function override the previous translate and don't combine the transformations. How then do I attain the effect I want?


Is this what are you are looking for: 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();

Note that you should use Math.PI/180 instead of that large decimal.
I also set your width and height properly on the canvas, and changed your setTimeout to not use eval().

0

精彩评论

暂无评论...
验证码 换一张
取 消