Get y point coordinate on svg path

I think I need to add some explanation that I want to ask this question, because a too short question does not meet the quality standards ... funny ...

So here is the question: How can I get the "y" coordinate of a point on the svg path with a specific "x" coordinate?

+4
source share
2 answers

Well, this is not easy, because a path can have several points with a specified coordinate x.

There is no built-in function for this in the SVG DOM. One solution is to move across the path segments and the math itself.

SVGPathElement, getPointAtLength(len). , , - . , x x. SVGPathElement.getTotalLength(). , , , x. .

. .

+10

, .

@Paul LeBeau, :

let path = document.getElementById("path");
let svg = document.getElementById("svg");

// The first important function getTotalLength
let totalLength = path.getTotalLength();
let intersections = 27;

for(var i = 0; i <= intersections; i ++){
  let distance = i * 1/intersections * totalLength;
  
  // The second important function getPointAtLength
  let point = path.getPointAtLength(distance);
  addCircleToSVG(point.x, point.y);
  addTextToSVG(point.x, point.y);
}

function addCircleToSVG(x, y){
  let circle = document.createElementNS("http://www.w3.org/2000/svg",'circle');
  circle.setAttribute("cx", x);
  circle.setAttribute("cy", y);
  circle.setAttribute("r", "5");
  circle.setAttribute("fill", "#8888ff");
  svg.appendChild(circle);
}

function addTextToSVG(x, y){
  let text = document.createElementNS("http://www.w3.org/2000/svg",'text');
  text.setAttribute("x", x + 10);
  text.setAttribute("y", y);
  text.setAttribute("fill", "orange");
  text.innerHTML = Math.round(y);
  svg.appendChild(text);
}
svg{
  width:auto;
  height: auto;
}
<svg id="svg" viewBox="0 0 1184.25 455.99">
  <path id="path" class="st0" d="M0.18,455.53c0,0,73-311,128-311s86,276,122,287s52-22,112-25s114,16,146,18s34,20,64,16s45-144,93-133
	s55-21,88-17s58,151,85,149s103-13,128-8s48-21,85-19c37,2,133,43,133,43" fill="#666666"/>
</svg>
Hide result
0

Source: https://habr.com/ru/post/1533329/


All Articles