Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

javascript - Draw a rotated element on a canvas

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...