Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 rotating an image with canvas

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').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>

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?

like image 917
Mike Avatar asked Aug 19 '11 05:08

Mike


People also ask

How do I rotate an image in HTML5?

Syntax: transform: rotate(90deg);

Which method is used to spin the logo image on the canvas?

HTML canvas rotate() Method.


1 Answers

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

like image 121
Digital Plane Avatar answered Oct 17 '22 21:10

Digital Plane