How SVG stroke-miterlimit Prevents Sharp Spikes
The stroke-miterlimit property in SVG is a threshold
mechanism designed to control the appearance of sharp corner junctions.
When two stroked lines meet at an acute angle using a miter join, the
outer corner can extend outward into an excessively long, sharp spike.
The stroke-miterlimit property sets a mathematical limit on
how far this spike can extend relative to the stroke width; if the
corner exceeds this threshold, the renderer automatically truncates the
sharp spike and converts the corner into a flat, beveled join.
The Mechanics of a Miter Join
When stroke-linejoin is set to miter, the
outer boundaries of two meeting line segments are extended until they
intersect. The distance from the point where the inner edges meet to the
sharp outer tip of the corner is defined as the miter
length.
As the angle between two connected lines becomes sharper (smaller), the intersection point of their outer edges moves exponentially farther away from the path itself. Without a limiting mechanism, acute angles on thick strokes produce massive, needle-like projections that distort the intended shape and can extend far outside the SVG’s viewport.
The Miter Ratio Calculation
SVG engines determine whether to clip a corner by calculating the
miter ratio, which is the ratio of the miter length to
the stroke-width:
\[\text{Miter Ratio} = \frac{\text{Miter Length}}{\text{Stroke Width}} = \frac{1}{\sin\left(\frac{\theta}{2}\right)}\]
In this formula, \(\theta\) represents the angle between the two connecting line segments. As the angle (\(\theta\)) approaches zero, the sine value decreases, causing the miter ratio to increase rapidly toward infinity.
How stroke-miterlimit Intervenes
The stroke-miterlimit attribute accepts a unitless
number (greater than or equal to 1) that acts as the maximum allowable
miter ratio.
During rendering, the SVG engine performs a simple evaluation at every corner:
- It calculates the corner’s miter ratio based on the angle of the path.
- It compares the calculated ratio against the specified
stroke-miterlimitvalue. - If the ratio is less than or equal to the limit, the corner renders as a sharp miter join.
- If the ratio exceeds the limit, the miter is
instantly converted to a
beveljoin, flattening the apex of the corner and preventing the spike from forming.
Default Value and Practical Behavior
The default value for stroke-miterlimit in SVG is
4.
A value of 4 permits miter joins on any angle down to
approximately 28.96 degrees. Any junction with an inner angle tighter
than ~29° automatically converts to a beveled edge. Increasing the value
allows sharper corners to retain their points, while setting the value
to 1 forces nearly all corners to bevel unless the path is
completely straight.