Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 50 ยท Line and Circle Algorithms

Thick Lines, Dashes and Pen Styles

Draw wide lines correctly: pixel replication and its flaws, line caps and joins, miter limits, dash patterns and the Canvas 2D line style properties.

So far every line has been one pixel wide. Real drawings need thick strokes, dashed borders, rounded ends and neat corners. Each of these sounds minor, but they raise real questions. How wide is a diagonal line that is "3 pixels wide"? What shape should the end of a stroke have? What happens at the corner where two thick segments meet? How long is a dash on a diagonal?

Graphics systems answer with a small vocabulary of pen attributes: width, cap style, join style and dash pattern. Vector formats (SVG, PDF, PostScript) and the Canvas 2D API all use the same vocabulary. In this lesson we first see the Canvas properties, then build thick lines in software to understand what the browser is doing for you.

Line width, caps and joins

ctx.lineWidth sets the thickness in canvas units. A stroke is centered on the path: half the width falls on each side, so a path along the pixel edge with lineWidth = 1 is smeared across two pixel columns at half intensity (which is why crisp 1-pixel canvas lines need a +0.5 offset).

The cap is the shape at the open end of a stroke:

lineCap Shape Extends beyond the end point
butt (default) flat edge exactly at the end 0
square flat edge pushed outward half the width
round semicircle half the width

The join is the shape at a corner between two segments:

lineJoin Shape
miter (default) the outer edges are extended until they meet in a sharp point
bevel the outer corner is cut flat
round the outer corner is a circular arc

A miter join gets very long at sharp angles. If the interior angle between the segments is theta, the miter tip sticks out by a ratio of 1 / sin(theta / 2) times the line width. To stop needle-like spikes, ctx.miterLimit (default 10) caps that ratio. When it is exceeded, the join silently falls back to a bevel.

flowchart TB
  P["Pen attributes"] --> W["Width"]
  P --> C["Caps<br/>butt, square, round"]
  P --> J["Joins<br/>miter, bevel, round"]
  P --> D["Dash pattern<br/>and offset"]
  J --> M["Miter limit<br/>(falls back to bevel)"]

Four attributes describe how a path becomes a stroke.

The first example draws all of these with guide marks. Thin red lines show where the path actually is, so you can see how far each cap reaches beyond it and how the joins differ. The slider changes the angle of the last shape so you can watch the miter turn into a bevel once the miter limit is exceeded.

Caps, joins and miter limit

Reading the canvas: the square cap reaches 12 units past the red end point (half of 24), butt stops on it. Move the angle slider down until the ratio crosses the limit and the sharp tip is chopped off.

Dashes

ctx.setLineDash([on, off, ...]) defines a repeating pattern of dash and gap lengths, measured along the path. An array with an odd number of values is repeated to make an even count: [5] behaves like [5, 5], and [10, 4, 2] like [10, 4, 2, 10, 4, 2]. An empty array restores solid lines. ctx.lineDashOffset moves the starting point of the pattern. Changing it frame by frame makes the dashes crawl along the path, the classic "marching ants" selection outline. Caps apply to every dash, so a round cap with a tiny dash length draws a row of dots.

Dash patterns and marching ants

Thick lines in software

The browser draws wide strokes with a polygon-based stroker. A simple software rasterizer usually starts with something much cruder: run Bresenham for the center line and replicate pixels perpendicular to the main direction. For a gentle line (more horizontal than vertical), each x column gets w pixels stacked vertically. For a steep line, each row gets w pixels side by side.

This is quick and works with any pixel algorithm, but it has a flaw. The replicated run is vertical (or horizontal), while the line's width should be measured perpendicular to its direction. For a line at angle theta from the x axis, a vertical run of w pixels has a perpendicular thickness of only w * cos(theta). On a diagonal at 45 degrees the line is about 29 percent too thin. The fix is to scale the run length by 1 / cos(theta), or equivalently by length / max(|dx|, |dy|).

flowchart LR
  A["Center line<br/>(Bresenham)"] --> B["For each step<br/>replicate across the minor axis"]
  B --> C["Run length = w<br/>(too thin on diagonals)"]
  B --> D["Run length = w * len / max(|dx|, |dy|)<br/>(constant width)"]

Naive replication gets thinner as the line tilts; the corrected run length keeps the width constant.

Another way is a pen: stamp a shape (a square or disc) at every pixel of the center line. A square pen has the opposite problem: its corners stick out, so a diagonal stroke measures wider than a horizontal one. A round pen gives the same width in every direction, which is why it is used for brush strokes.

The exact method treats the stroke as geometry: offset the two end points by the unit normal times w / 2 on each side, producing a rectangle, then fill that polygon with scanline filling. Caps and joins then become extra triangles or arcs added at the ends and corners.

The next example draws the same fan of lines with naive and corrected replication and prints the true perpendicular widths.

Pixel replication vs corrected width

Dashes in software

A rasterizer typically implements dashes with a mask applied while walking the line: a repeating bit pattern such as 11110000 where a 1 means "draw this pixel". It is cheap, but the unit is the pixel step, not distance. On a horizontal line a step covers 1 unit; on a 45-degree line a step covers sqrt(2) units, so the dashes come out about 41 percent longer. Vector renderers instead count the arc length along the path, which is why Canvas dashes keep the same size at any angle.

JS Dash length depends on direction

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Putting it together

  • For a UI or chart, use the Canvas properties and let the browser do the geometry.
  • For crisp 1-pixel lines, stroke at half-pixel coordinates, or draw with the integer algorithms and skip antialiasing.
  • For software rendering of thick lines, prefer the polygon method for correctness and replication for speed, and add antialiasing if the edges matter.
  • For dashed curves, measure distance along the curve, not in screen pixels. Dashes on a Bezier curve use arc length too.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A stroke has lineWidth 20 and lineCap square. How far does it extend beyond its end point?

    Square and round caps extend by half the line width. Half of 20 is 10.
  2. 2. Why is a diagonal line made with naive pixel replication thinner than a horizontal one?

    A vertical run of w pixels has perpendicular thickness w*cos(theta), which is smaller than w for tilted lines.
  3. 3. What does the Canvas do when a miter join's ratio exceeds miterLimit?

    To avoid long spikes at sharp corners the join falls back to a bevel.
  4. 4. What does ctx.setLineDash([4]) produce?

    An odd-length array is repeated to make an even one, so [4] means [4, 4].
  5. 5. Why do pixel-mask dashes look longer on a 45-degree line?

    The mask counts pixel steps, and a diagonal step spans sqrt(2) units, so every dash is about 41 percent longer.

Summary

  • A stroke is described by width, cap style, join style and a dash pattern.
  • Caps (butt, square, round) shape the ends; joins (miter, bevel, round) shape the corners; miterLimit turns long miters into bevels.
  • setLineDash and lineDashOffset control dashes, measured along the path.
  • Replicating pixels perpendicular to the major axis is fast but makes tilted lines thinner unless the run length is scaled by length / max(|dx|, |dy|).
  • Exact thick lines are polygons: offset the center line by half the width along its normal.
  • Dash patterns defined per pixel vary in length with direction; arc-length patterns do not.

Next: Polygons: Types and Representation.