user1044445
user1044445

Reputation: 21

How does canvas 2dContext.translate(...) actually work?

I am trying create an app using OnTouchListener and 2dContext.translate, with 2dContext = canvas.getContext('2d').
The listener will change pan values when the user touches the screen and canvas.translate new coordinates.

And now I solve a small problem, how does 2dContext.translate actually work.
E.g.: I set first coord using 2dContext.translate(100,100), it is no pan, but real coord in a view. The second coord in the view are [400,400]. What is right, 2dContext.translate(400,400) or 2dContext.translate(300,300)?

I mean, do I have to set new coord to last coord like pan (100+300) or do I have to set second coord like fully new coord (400)? Do the coords have relative or absolute value in this case?

Upvotes: 1

Views: 1230

Answers (1)

Xenethyl
Xenethyl

Reputation: 3199

Every translation is relative to the current origin. If you call ctx.translate(x, y), your origin will shift x pixels in the x direction and y pixels in the y direction. Both positive and negative values are accepted.

If you need to maintain varying origin positions, use ctx.save() and ctx.restore() to remember and reset previously-defined canvas attributes. These functions operate on a stack, so you can save multiple states.

Upvotes: 2

Related Questions