Reputation: 11
I need to display a few images which will be one on top of the other in some parallel areas. What is the right way to do it if each image should be rotated in a different angle and located in different coordinates (x,y)?
Do I need to draw them on a single canvas and somehow rotate them differently in that canvas, or should I create different canvas for each image? once I created different canvas for each image, it displayed only the last image and the canvases were one next to the other with no parallel areas..
Thanks...
Upvotes: 1
Views: 831
Reputation: 2034
canvas has those very useful transforms that you can use.
What you need right now is canvas' .translate
and .rotate
Let's say you make a function which takes an img
image, x
coordinate, y
coordinate and rad
rotation to your top left corner argument, this is how you'd do it:
function displayRotatedImage( img, x, y, rad ){
ctx.translate( x, y ); // ctx is your canvas context
ctx.rotate( rad );
ctx.drawImage( img, 0, 0 );
ctx.rotate( -rad ); // don't forget to get everything to its previous state!
ctx.translate( -x, -y );
}
Do you see what's going on? first of all we move to the pivot of the rotation using .translate
, then we rotate around that pivot using .rotate
, and we draw our image relatively to our system, and since 0 0 is our pivot point now, thanks to the translate, we simply draw the image at 0 0. Now we have to derotate and detranslate to get the canvas to it's original transform ;)
Upvotes: 2