1

I just wonder how do the Canvas transformations work. Lets say i have a canvas with a circle drawn somewhere inside of it, and i want to scale the circle, so its center point will not move. So i thought about doing 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 way to do it? I just don't understand whether the canvas was designed to remember the order that i call the transformations.

Thanks.

gipouf
  • 1,221
  • 3
  • 15
  • 43
  • to zoom-in into where the mouse cursor is pointing. – gipouf May 23 '13 at 19:56
  • 1
    To completely understanding how transformations occur in canvas I recommend the following article: [MDN Canvas Tutorial - Transformations](https://developer.mozilla.org/en-US/docs/Web/HTML/Canvas/Tutorial/Transformations?redirectlocale=en-US&redirectslug=HTML%2FCanvas%2FTutorial%2FTransformations). This is part of [MDN Canvas Tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML/Canvas/Tutorial). – Gustavo Carvalho May 23 '13 at 20:33

1 Answers1

2

Yes, you are correct.

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

So if you scale 2X, your circle will be drawn at 2X…and(!) every draw after that will be 2X.

That’s where saving the context is useful.

If you want to scale your circle by 2X but then have every subsequent drawing be at normal 1X you can use this pattern.

// 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 translate and scale will not apply to further drawings.

markE
  • 102,905
  • 11
  • 164
  • 176