HTML5 Canvas Image Rotation

12,088

Solution 1

Yes you can, but it's not as simple as setting a rotation attribute. The way canvas works you can't rotate individual items specifically, only the whole canvas.

To rotate a single item, you'll need to rotate the canvas, place the item, and then rotate the canvas back to it's original orientation.

This question has a few examples: How do I rotate a single object on an html 5 canvas?

Solution 2

Before placing the image on the canvas, create a buffer canvas, place image there, rotate it and then port to main canvas.

var canvas = document.getElementById('test_canvas');
var ctx = canvas.getContext('2d');

var buffer = document.createElement('canvas');
buffer.width = buffer.height = 60;
var bctx = buffer.getContext('2d');
bctx.translate(30, 30);
bctx.rotate(0.5);
bctx.fillStyle = 'rgb(255, 0, 0)';
bctx.fillRect(-15, -15, 30, 30);

ctx.fillStyle = 'rgb(0, 255, 0)';
ctx.fillRect(30, 30, 30, 30);
ctx.drawImage(buffer, 50, 50);

You can check this code at JSFiddle I've setup - http://jsfiddle.net/dzenkovich/UdaUA/2/

Note you'll need to keep a close eye at the rotation point and buffer canvas size for this to work. For more info check out this article I've found http://creativejs.com/2012/01/day-10-drawing-rotated-images-into-canvas/

Share:
12,088
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a canvas where i have drawn a series of images onto it that can be dragged and dropped around, each image is a seperate entity.

    I need to, depending on where the image is dropped rotate that image so that it looks appropiate, imaging dragging a triangle around a circle, the base line needs to always point outwards.

    I thought i would be able to rotate the image and then draw that on the canvas, but what i seem to find when searching on the internet is that the canvas rotates each time - is it possible to rotate the image only and then place it on the canvas?

    Many Thanks!