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
Asked
Active
Viewed 4.5k times
37
-
possible duplicate of [Canvas rotate from bottom center image angle?](http://stackoverflow.com/questions/365382/canvas-rotate-from-bottom-center-image-angle) – Gabriele Petrioli Jan 10 '11 at 18:02
1 Answers
95
In general, what you want to do is:
- Transform the context to the point on the canvas that the object should rotate about.
- Rotate the context.
- Transform the context by the negative offset within the object for the center of rotation.
- 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.

Andreas Grech
- 105,982
- 98
- 297
- 360

Phrogz
- 296,393
- 112
- 651
- 745
-
1
-
1For further discussion, see this (duplicate) question and answer: [HTML5 Canvas `drawImage` at an angle](http://stackoverflow.com/questions/3793397/html5-canvas-drawimage-with-at-an-angle). – Phrogz Jan 10 '11 at 20:53
-
Still stuck when it comes to replacing the parameters in rotate() method to incorporate feed from data structure. – Abhijit Jan 11 '11 at 16:43
-
1@Ab Perhaps you are receiving degrees and passing them to `rotate()` without first converting them to radians? If so, multiply by `Math.PI/180`. If that doesn't help, edit your question with a pared-down test case showing your actual code and we can move forward from there. – Phrogz Jan 11 '11 at 16:57
-
-