简体   繁体   中英

How to set canvas translation to top left corner after rotation

I'm drawing a symbol with simple lines, but want the user to be able to specify the rotation (in 90degrees only). Which also means that the dimensions of my canvas change.

No I calculate the dimensions, and set the canvas size. Then I set the center of the rotation to the center of my canvas (via ctx.translate ) and rotate to the arbitrary degrees.

Now my problem is: How do I set the translation back to the upper left corner, so I can draw my symbol normally from that position? Do I really have to calculate the values with the rotation?

Thanks.

Great question! translate rotate and scale are all functions that operate upon the current matrix. This gives you lots of options. Probably the simplest thing is to do a save restore on the context matrix

ctx.save();
ctx.translate ( to the center );
ctx.rotate ( do rotation );
//Draw rotated stuff
ctx.restore();
//Draw non-rotated stuff

Now after you call restore, the matrix reverts to how it was before the last save - In opengl, this is actually a stack, and you can push many contexts, but I'm not sure if webgl supports that.

This link may also be helpful: https://developer.mozilla.org/en/drawing_graphics_with_canvas

Hope this helps.

Update:

Yes. Okay, so you are misunderstanding something a little bit. The translations and rotations are applied before the drawing. This is because of a lot of complex math, and is really beyond the scope of this question. So if you want to draw part of your canvas rotated one way, and the other part of it rotated a different way, you first save , then apply the transformations, do the first part of the drawing, then restore to get back to the pre-transformed state. At which point, you can repeat. So, for example, you can do this:

ctx.save();
ctx.translate ( x_center, y_center );
ctx.rotate ( 90 );
//Draw your rotated stuff starting at the center
ctx.translate ( -x_center, -y_center );
//Draw your main frame stuff that is all rotated around the center
ctx.restore();
ctx.save();
ctx.rotate ( 90 );
//Draw your text which is rotated around the top-left corner
ctx.restore();

In this way, you have 1 drawing function, and you simply setup a context before you draw the different components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM