HTML5 canvas - mixing multiple translate () and scale () calls

I'm just wondering how Canvas transformations work. Let's say I have a canvas with a circle drawn somewhere inside it, and I want to scale the circle so its center point won't move. So I thought about the following:

translate(-circle.x, -circle.y);
scale(factor,factor);
translate(circle.x,circle.y);

// Now, Draw the circle by calling arc() and fill()

      

Is it the right thing to do? I just don't understand if the canvas was meant to remember the order that I call transformations.

Thank.

0


source to share


1 answer


Yes you are right.

The canvas accumulates all transformations and applies them to any future drawing.

So if you scale it 2X, your circle will be drawn 2X ... and (!) Every draw thereafter will be 2X.

Preserving context is helpful here.



If you want to scale the circle by 2X, but then each subsequent drawing will be in normal 1X, you can use this template.

// save the current 1X context
Context.save();

// move (translate) to where you want your circle’s center to be
Context.translate(50,50)

// scale the context
Context.scale(2,2);

// draw your circle
// note: since we’re already translated to your circles center, we draw at [0,0].
Context.arc(0,0,25,0,Math.PI*2,false);

// restore the context to it’s beginning state:  1X and not-translated
Context.restore();

      

After Context.restore, your translation and scale will not be applied to additional drawings.

+1


source







All Articles