Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In HTML5 canvas, what is the difference between the translate() and moveTo() javascript functions?

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?

like image 772
Someone Avatar asked Oct 03 '13 00:10

Someone


People also ask

What is moveTo in canvas?

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);

What is canvas translate in JavaScript?

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.

What is translate in canvas?

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.

What does moveTo X Y method used for in canvas?

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.


2 Answers

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! :)

like image 116
Super Fighting Robot Avatar answered Sep 30 '22 20:09

Super Fighting Robot


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.

like image 28
Niet the Dark Absol Avatar answered Sep 30 '22 19:09

Niet the Dark Absol