Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to draw a semi-complex element on a canvas rotated without rotating the canvas so that I don't need to calculate all of the various x/y points of the element.

I think that the basic process I need to use is:

  • translate the 0,0 point to the spot the drawn element will be rotated around,
  • rotate the canvas,
  • draw the element,
  • rotate the canvas back,
  • restore the origin point.

I will need to do this more than once. I've read that the rotate / rotate back part can introduce some error, with the final image being off just a bit. Is there a way to avoid this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
193 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...