1

W3C SVG Strokes introduces stroke-dashadjust but no browser implements it yet.

Adobe Illustrator's stroke panel has a button for this feature – its tooltip reads Aligns dashes to corners and path ends, adjusting lengths to fit

When you set it and export SVG what it does is take your initial settings, say 0pt dash, 5pt gap and tweak them, outputting a stroke-dasharray attribute like 0,4.9121.

I wanted to use this for connecting text with plots on charts, before support for this new attribute arrives in browsers. My use case only involved straight lines (so not worrying about paths with corners yet): connecting label text with bars in a bar chart.

More details:
Proposals/Stroke dash adjustment - SVG

1 Answer 1

1

I wanted to ask but then I figured it out:

// Select your lines and convert to array
const linesArray = [...document.querySelector('svg path.straight-line')];

linesArray.forEach(line => {
  const len = line.getTotalLength();
  // Compute stroke-dasharray attribute values
  const dasharray = (len, gap) => {
    // How many segments?
    return (len%gap < gap/2)
      // Is it closer to go lower?
      ? +(len / Math.floor(len/gap)).toFixed(4) - 0.01
      // or higher?
      : +(len / Math.ceil(len/gap)).toFixed(4) - 0.01;
  };
  line.setAttribute('stroke-dasharray', `0,${dasharray(len, 5)}`);
});

Uses SVGPathElement.getTotalLength which has sketchy support itself... It can be replaced with parsing the path's d attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.