The Canvas 2D API offers us the possibility to draw paths and sub-paths to create different shapes and figures.

To initiate a new path we have to call the beginPath() method from the CanvasRenderingContext2D object.

index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Paths in Canvas API</title>
    </head>
    <body>
        <canvas id="canvas">
            drawing of a line, triangle & cube
        </canvas>

        <script src="index.js"></script>
    </body>
</html>
index.js
const canvas = document.getElementById("canvas")
const context = canvas.getContext("2d")

context.beginPath()

Now that we have created a new path, we can start drawing some lines. To do that, first let’s move our graphics paintbrush to the (x, y) coordinates we want.

context.moveTo(140, 72)

From that starting point let’s draw a straight line to another (x, y) coordinates we want. To achieve this we need to call the lineTo() method. This connects the last point, in our example P(140, 72), to the specified (x, y) coordinates.

context.lineTo(45, 23)

We still cannot see anything. The reason why is that this method doesn’t render anything, we must then call the stroke() method.

context.stroke()

Here’s the result:

line

Drawing a triangle

context.beginPath()
context.moveTo(200, 120)
context.lineTo(233, 99)
context.lineTo(199, 145)
context.closePath()
context.stroke()

line & triangle

Notice the closePath() method. This adds a line from the current point, in our case O(199, 145), to the starting point of the current sub-path, in our example is the point M(200, 120), to close the triangle.

Drawing a cube

context.beginPath()
context.moveTo(170, 80)
context.lineTo(170, 40)
context.lineTo(210, 40)
context.lineTo(210, 80)
context.closePath()
context.moveTo(170, 40)
context.lineTo(185, 15)
context.lineTo(225, 15)
context.lineTo(210, 40)
context.moveTo(225, 15)
context.lineTo(225, 55)
context.lineTo(210, 80)
context.stroke()

line, triangle & cube

Challenge

  1. Try to draw a basic figure of your own choice.