Coordenadas no Canvas HTML
- Página Anterior Desenho no Canvas
- Próxima Página Linha no Canvas
Canvas coordinates
The HTML canvas is a two-dimensional grid.
The top-left corner of the canvas is at (0,0).
In the previous chapter, we used the method: fillRect(0,0,150,75).
This means: draw a 150x75 pixel rectangle starting from the top-left corner (0,0).
Coordinate example
Hover your mouse over the following rectangle to view its x and y coordinates:
Draw a line
To draw a straight line on the canvas, use the following methods:
- moveTo(x,y) - Define the starting point of the line
- lineTo(x,y) - Define the endpoint of the line
To actually draw a line, you must use one of the 'paint' methods, such as stroke().
Example
Define the starting point at position (0,0) and the endpoint at position (200,100). Then use the stroke() method to actually draw the line:
const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); ctx.moveTo(0, 0); ctx.lineTo(200, 100); ctx.stroke();
Draw a circle
To draw a circle on the canvas, use the following methods:
- beginPath() - Start a path
- arc(x,y,r,startangle,endangle) - Create an arc/circle
To create a circle using arc(): set the start angle to 0, and the end angle to 2 * Math.PI. The x and y parameters define the x and y coordinates of the circle's center. The r parameter defines the radius of the circle.
Example
Use the arc() method to define a circle. Then use the stroke() method to actually draw the circle:
const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.arc(95, 50, 40, 0, 2 * Math.PI); ctx.stroke();
Veja também:
- Página Anterior Desenho no Canvas
- Próxima Página Linha no Canvas