Shapes in HTML Canvas
- Previous Page Canvas Line
- Next Page Canvas Rectangle
Instance
Example 1
const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(20,20); ctx.lineTo(100,20); ctx.lineTo(175,100); ctx.lineTo(20,100); ctx.lineTo(20,20); ctx.stroke();
Canvas Line Drawing
Line drawing uses paths in the canvas:
The method | Description | Draw |
---|---|---|
beginPath() | Start a new path. | No |
moveTo() | Move to a point. | No |
lineTo() | Draw a line to another point. | No |
stroke() | Drawing. | Is |
The method
beginPath()
The method starts a new path. It does not draw anything, it just defines a new path.
moveTo()
Define the start point of a line. It does not draw anything, it just sets a start point.
lineTo()
The method defines the end point of a line. It does not draw anything, it just sets an endpoint.
stroke()
The method actually draws lines. The default stroke color is black.
More examples
Example 2
ctx.beginPath(); ctx.moveTo(100,20); ctx.lineTo(175,100); ctx.lineTo(20,100); ctx.lineTo(100,20); ctx.stroke();
Example 3
ctx.beginPath(); ctx.moveTo(20,20); ctx.lineTo(175,20); ctx.lineTo(175,100); ctx.lineTo(20,100); ctx.lineTo(20,20); ctx.stroke();
Hint
If you want to draw a rectangle, you do not need to draw 4 lines.
In the next chapter, you will learn to use drawRect()
method to draw a rectangle.
strokeStyle attribute
strokeStyle
The attribute defines the style to be used when drawing on the canvas.
Must be called stroke()
Set it before the method.
Instance
ctx.beginPath(); // Define rectangle ctx.moveTo(20,20); ctx.lineTo(175,20); ctx.lineTo(175,100); ctx.lineTo(20,100); ctx.lineTo(20,20); // Define triangle ctx.moveTo(100,20); ctx.lineTo(175,100); ctx.lineTo(20,100); ctx.lineTo(100,20); ctx.strokeStyle = "red"; ctx.stroke();
See Also:
- Previous Page Canvas Line
- Next Page Canvas Rectangle