Use SVG to Create Lines

Jhey Tompkins
InstructorJhey Tompkins
Share this video with your friends

Social Share Links

Send Tweet

Use SVG to create lines with the path element. We can hand-code a path definition and set a stroke width and stroke linecap. We can adjust the path definition to accommodate for the SVG viewBox.

Instructor: [0:00] Our tic-tac-toe board needs lines. To create them, we can use SVG. We need four lines, so we can use a for loop. Let's do for (let l = ; l < 4; l++). For each iteration, we're going to create an SVG with the class boardLine. We're going to set a viewBox for our SVG, and let's go with " 10 300".

[0:24] Then, we're going to use a path element. Then we're going to set a d attribute, which defines the path to be drawn. We're going to move to the point 5,5. Then, we're going to draw a line to point 5,295. Then, we're going to define a stroke-width of 10, a stroke-linecap of "round", and a stroke of "black".

[0:51] That creates a huge SVG. Let's apply some styles, so we can see what we have. Let's also give our line a temporary background of "red", and if we look closely, we can see the bounds of our line element with these red corners.

[1:05] For our line, we're using a path. We're defining for our path that we move to point 5,5. Then, we draw a line down to 5,295. The reason we don't go from , to ,300 is because we're using a stroke-width of 10 and a linecap of "round", and we want to see the linecap.

[1:23] If we update the line's move to 5,, we can see that we lose the linecap. If we apply overflow: visible, we can see the linecap coming out of the bounds.

[1:33] In review, we can use SVG to create lines. We can use the path element with a definition that draws a line within the bounds of our SVG. Here, we're using the Move command to move to point 5,5 and then draw a line to 5,295. In doing so, we should be mindful of our stroke-width and stroke-linecap. Here, we adjust the path definition relative to the viewBox in order to see the linecap.