Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas rotate from bottom center image angle?

How do you rotate an image with the canvas html5 element from the bottom center angle?

<html>
    <head>
        <title>test</title>
        <script type="text/javascript">
            function startup() {
                var canvas = document.getElementById('canvas');
                var ctx = canvas.getContext('2d');
                var img = new Image();
                img.src = 'player.gif';
                img.onload = function() {
                    ctx.translate(185, 185);
                    ctx.rotate(90 * Math.PI / 180);
                    ctx.drawImage(img, 0, 0, 64, 120);
                }
            }
        </script>
    </head>
    <body onload='startup();'>
        <canvas id="canvas" style="position: absolute; left: 300px; top: 300px;" width="800" height="800"></canvas>
    </body>
</html>

Unfortunately this seems to rotate it from the top left angle of the image. Any idea?

Edit: in the end the object (space ship) has to rotate like a clock pointer, as if it is turning right/left.

like image 263
Tom Avatar asked Dec 13 '08 16:12

Tom


People also ask

How do I rotate an image without rotating canvas?

Another way to rotate an image without rotating the canvas is to use the Free Transform tool. To do this, go to Edit > Free Transform, or press Ctrl+T (Windows) / Command+T (Mac). Then, click and drag one of the corner handles of the bounding box around the image. As you drag, you'll see the image rotate.

How do I reset my canvas orientation?

It's called Canvas Rotation. You can reset via the View menu / Canvas Orientation / Reset Rotation.

How do you rotate a path in canvas?

Choose the Rotate tool to rotate path points around a reference point. To rotate one or more path points, first select the path points using the Path Selection tool. With the Rotate tool active, click and drag anywhere on the canvas to rotate the path points clockwise or counterclockwise.


1 Answers

First you have to translate to the point around which you would like to rotate. In this case the image dimensions are 64 x 120. To rotate around the bottom center you want to translate to 32, 120.

ctx.translate(32, 120);

That brings you to the bottom center of the image. Then rotate the canvas:

ctx.rotate(90 * Math.PI/180);

Which rotate by 90 degrees.

Then when you draw the image try this:

ctx.drawImage(img, -32, -120, 64, 120);

? Does that work?

like image 172
Vincent Ramdhanie Avatar answered Sep 28 '22 21:09

Vincent Ramdhanie