Before you perform the rotation and translation, call context.save()
. This will create a snapshot of the current transformation of the canvas (as well as some other things, like drawing style, clip region, etc., but not the pixel data) and store it on a stack.
After you drew the shape, call context.restore()
. This will pop the last saved state from the state stack and restore the current drawing state of the canvas to it.
You can do this as often as you want without accumulating any rounding differences.
Example function:
function drawImageRotated(x, y, rotation, image) {
context.save();
context.translate(x, y);
context.rotate(rotation);
context.drawImage(image, -image.width / 2, -image.height / 2);
context.restore();
// context translation and rotation are now on the same state they were
// before the function call
}
For more information about the canvas state, refer to the canvas specification.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…