0
0
HtmlHow-ToBeginner · 3 min read

How to Create a Line in SVG: Simple Guide with Examples

To create a line in SVG, use the <line> element with attributes x1, y1, x2, and y2 to set the start and end points. Style the line using the stroke and stroke-width attributes to control its color and thickness.
📐

Syntax

The <line> element draws a straight line between two points in SVG. The main attributes are:

  • x1: The x-coordinate of the line's start point.
  • y1: The y-coordinate of the line's start point.
  • x2: The x-coordinate of the line's end point.
  • y2: The y-coordinate of the line's end point.
  • stroke: The color of the line.
  • stroke-width: The thickness of the line.
html
<line x1="startX" y1="startY" x2="endX" y2="endY" stroke="color" stroke-width="thickness" />
💻

Example

This example shows a black diagonal line from the top-left corner to the bottom-right corner inside an SVG canvas of 200 by 200 pixels.

html
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <line x1="0" y1="0" x2="200" y2="200" stroke="black" stroke-width="2" />
</svg>
Output
A 200x200 pixel square with a thin black diagonal line from top-left to bottom-right.
⚠️

Common Pitfalls

Common mistakes when creating lines in SVG include:

  • Forgetting to set the stroke attribute, which makes the line invisible because the default stroke is none.
  • Using coordinates outside the SVG canvas size, so the line is not visible.
  • Setting stroke-width too small or too large, making the line hard to see or overwhelming.
html
<!-- Wrong: No stroke, line won't show -->
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  <line x1="10" y1="10" x2="90" y2="90" />
</svg>

<!-- Right: Add stroke and stroke-width -->
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  <line x1="10" y1="10" x2="90" y2="90" stroke="blue" stroke-width="3" />
</svg>
📊

Quick Reference

Remember these key points when creating lines in SVG:

  • Coordinates: Use x1, y1, x2, y2 to set start and end points.
  • Stroke: Always set stroke color to make the line visible.
  • Thickness: Use stroke-width to control line thickness.
  • SVG Canvas: Ensure coordinates fit inside the SVG width and height.

Key Takeaways

Use the element with x1, y1, x2, y2 to define the line's start and end points.
Always set the stroke color to make the line visible.
Adjust stroke-width to control the line's thickness.
Keep coordinates within the SVG canvas size to ensure visibility.
Without stroke, the line will not appear even if coordinates are correct.