Skip to content Skip to sidebar Skip to footer

Html5 Canvas Image Rotation

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 dr

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/

Post a Comment for "Html5 Canvas Image Rotation"