Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using HTML5 Canvas - rotate image about arbitrary point

Rotate the dial on top of a semi circular(Northern Hemisphere) image as background. range could be 0 - 180 degrees. on input to the method that does canvas transformation, the dial would rotate and stop over the matched value. Here's what I was trying based on help and sample passed on by phrogz

like image 809
Abhijit Avatar asked Jan 10 '11 17:01

Abhijit


People also ask

How do I rotate an image in HTML5?

Syntax: transform: rotate(90deg);

How do you rotate a Rectanger in canvas?

To do that you need to first context. translate to the rect's centerpoint before rotating. // move the rotation point to the center of the rect ctx. translate( x+width/2, y+height/2 ); // rotate the rect ctx.

How do you rotate shapes in canvas?

To rotate a shape around its own center, you must first translate the canvas to the center of the shape, then rotate the canvas, then translate the canvas back to 0,0, and then draw the shape. This example first translates (moves) the center of the canvas to the center of the square (cx, cy).


1 Answers

In general, what you want to do is:

  1. Transform the context to the point on the canvas that the object should rotate about.
  2. Rotate the context.
  3. Transform the context by the negative offset within the object for the center of rotation.
  4. Draw the object at 0,0.

In code:

ctx.save(); ctx.translate( canvasRotationCenterX, canvasRotationCenterY ); ctx.rotate( rotationAmountInRadians ); ctx.translate( -objectRotationCenterX, -objectRotationCenterY ); ctx.drawImage( myImageOrCanvas, 0, 0 ); ctx.restore(); 

Here's a working example showing this in action. (The math for the rotation was just experimentally hacked to find a swing amount and offset in radians that fit the quickly-sketched gauge dial.)

As may be evident, you can substitute the translate call in step #3 above with offsets to the drawImage() call. For example:

ctx.drawImage( myImageOrCanvas, -objectRotationCenterX, -objectRotationCenterY ); 

Using context translation is recommended when you have multiple objects to draw at the same location.

like image 120
Phrogz Avatar answered Sep 21 '22 05:09

Phrogz