Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 canvas drawImage with at an angle

I am experimenting with animation in <canvas> and can't work out how to draw an image at an angle. The desired effect is a few images drawn as usual, with one image rotating slowly. (This image is not at the centre of the screen, if that makes any difference).

like image 682
Greg Avatar asked Sep 25 '10 10:09

Greg


People also ask

How do you rotate elements in canvas?

Introduction to JavaScript rotate() canvas APIThe rotate() method allows you to rotate a drawing object on the canvas. The rotate() method accepts a rotation angle in radians. If the angle is positive, the rotation is clockwise. In case the angle is negative, the rotation is counterclockwise.

What is CTX drawImage?

The drawImage() method is a method from the Canvas API that allows you to add an image into your <canvas> element. Just like the fillRect() method, the drawImage() method is a part of Canvas 2D API, so you need to get the Context object of your <canvas> element first and call the method from there.


2 Answers

You need to modify the transformation matrix before drawing the image that you want rotated.

Assume image points to an HTMLImageElement object.

var x = canvas.width / 2; var y = canvas.height / 2; var width = image.width; var height = image.height;  context.translate(x, y); context.rotate(angleInRadians); context.drawImage(image, -width / 2, -height / 2, width, height); context.rotate(-angleInRadians); context.translate(-x, -y); 

The x, y coordinates is the center of the image on the canvas.

like image 70
Jakub Wieczorek Avatar answered Sep 26 '22 23:09

Jakub Wieczorek


I have written a function (based on Jakub's answer) that allows user to paint an image in a X,Y position based on a custom rotation in a custom rotation point:

function rotateAndPaintImage ( context, image, angleInRad , positionX, positionY, axisX, axisY ) {   context.translate( positionX, positionY );   context.rotate( angleInRad );   context.drawImage( image, -axisX, -axisY );   context.rotate( -angleInRad );   context.translate( -positionX, -positionY ); } 

Then you can call it like this:

var TO_RADIANS = Math.PI/180;  ctx = document.getElementById("canvasDiv").getContext("2d"); var imgSprite = new Image(); imgSprite.src = "img/sprite.png";  // rotate 45º image "imgSprite", based on its rotation axis located at x=20,y=30 and draw it on context "ctx" of the canvas on coordinates x=200,y=100 rotateAndPaintImage ( ctx, imgSprite, 45*TO_RADIANS, 200, 100, 20, 30 ); 
like image 41
Yaume Avatar answered Sep 25 '22 23:09

Yaume