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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…