I am currently learning to use canvas, and do not understand the difference between these two functions. From what I have read, the translate method 'moves the canvas'? Can someone explain this?
Edit: Is moveTo only used within the context of a path?
The moveTo() method moves the path to the specified point in the canvas, without creating a line. Tip: Use the stroke() method to actually draw the path on the canvas. JavaScript syntax: context.moveTo(x,y);
The translate() is a method of a 2D drawing context. The translate(x,y) method moves the canvas and its origin x units horizontally and y units vertically. In this syntax: x represents the distance that you want to move the origin of the canvas in the horizontal direction.
The translate() method adds a translation transformation to the current matrix by moving the canvas and its origin x units horizontally and y units vertically on the grid.
moveTo() The CanvasRenderingContext2D. moveTo() method of the Canvas 2D API begins a new sub-path at the point specified by the given (x, y) coordinates.
To be a little more specific than Kolink, since I think the explanation is a little muddy;
-The coordinate you pass moveTo
is the starting point of a new line (or shape); As if picking up your pen off the paper and setting it in a new location (the new coordinates).
-The function of lineTo
is what "move(s) the pen across the paper to draw a line" (to a new coordinate you've given it, since you need two points to draw a line, obviously)
-You can place multiple lineTo
calls one after another and it will use the last point you ended on, to continue the line, like so:
ctx.moveTo(100,50);
ctx.lineTo(25,175);
ctx.lineTo(175,175);
ctx.lineTo(100,50);
ctx.stroke();
here's a simple fiddle showing the outcome: http://jsfiddle.net/fbZKu/
(you can even "fill" these shapes you make with ctx.fill()
!)
-The use of translate
is to move the canvas' (0,0) coordinate (upper left corner) to the new coordinate.
I hope that clears things up a bit more! Happy coding! :)
Imagine you are drawing on graph paper.
moveTo
means you take your pen and move it across the paper to draw a line.
translate
means you shift the position of the paper on the table.
They could not be more different functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With