Get point's y coordinate on svg path

前端 未结 3 1343
悲&欢浪女
悲&欢浪女 2021-02-10 16:35

I guess I need to add some explanation, that I want to ask this question, because too short question doesn\'t quality standards... funny...

So, here is the question: How

3条回答
  •  广开言路
    2021-02-10 17:01

    I was working on a similar problem and Paul's answer really helped me.

    Just to further illustrate @Paul LeBeau's answer, here is a little demo:

    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;
    }
    
      
    

提交回复
热议问题