Home > Enterprise >  Detect a click on a SVG line even at a distance of 3 pixels
Detect a click on a SVG line even at a distance of 3 pixels

Time:04-01

Here is how I detect clicks on SVG lines:

window.onmousedown = (e) => {
    if (e.target.tagName == 'line') {
        alert();  // do something with e.target
    }
}
svg line:hover { cursor: pointer; }
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" id="svg">
<line x1="320" y1="160" x2="140" y2="00" stroke="black" stroke-width="2"></line>
<line x1="140" y1="00" x2="180" y2="360" stroke="black" stroke-width="2"></line>
<line x1="180" y1="360" x2="400" y2="260" stroke="black" stroke-width="2"></line>
<line x1="00" y1="140" x2="280" y2="60" stroke="black" stroke-width="2"></line>
</svg>

It only works if the mouse cursor is precisely on the line, which is not easy, so it's a bad UX.

How to detect a click on a SVG line from Javascript, even if not perfectly on the line, but at a distance of <= 3 pixels?

CodePudding user response:

A bit tricky solution, but does the job:

window.onmousedown = (e) => {
    if (e.target.classList.contains('line')) {
        console.log(e.target.href);
    }
}
svg .line:hover {
  cursor: pointer;
}
.line {
  stroke: black;
  stroke-width: 2px;
}
.line.stroke {
  stroke: transparent;
  stroke-width: 6px;
}
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" id="svg">
    <defs>
      <line id="line1" x1="320" y1="160" x2="140" y2="00"></line>
      <line id="line2" x1="140" y1="00" x2="180" y2="360"></line>
      <line id="line3" x1="180" y1="360" x2="400" y2="260"></line>
      <line id="line4" x1="00" y1="140" x2="280" y2="60"></line>
    </defs>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line1" ></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line1" ></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line2" ></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line2" ></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line3" ></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line3" ></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line4" ></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line4" ></use>
</svg>

  • Related