根据鼠标光标位置显示的SVG曲线路径

时间:2021-02-02 08:54:31

标签: javascript css svg path onmouseover

我正在尝试根据鼠标位置绘制现有的 svg 曲线路径。

我找到了一个几乎实用的解决方案。这是:

let dasharray = 650;
let dashoffset = 0;
let svgWidth =   svgg.getBoundingClientRect().width;
let mouseSvgX;

document.getElementById('chemin').addEventListener('mousemove', function(e){

  
  mouseSvgX = e.clientX-svgg.getBoundingClientRect().left;
  
  rouge.style.strokeDashoffset = dasharray - (mouseSvgX/svgWidth)*dasharray;

  
   console.log('length : ' + this.getTotalLength());

 console.log('viewbox width : ' +  svgWidth );
})
path{fill:transparent;stroke:black;stroke-width:10;}
path#chemin{
  fill:none;stroke:black;stroke-width:3;
}
path#rouge{
  stroke:red; stroke-linejoin:miter-clip;stroke-linecap:round;
  stroke-dasharray:650; stroke-dashoffset:325;
}
<svg  id='svgg' version="1.0" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 381.4 167.9" style="enable-background:new 0 0 381.4 167.9;" xml:space="preserve">
  <path id="rouge" d="M2.5,53.4C2.8,28.2,8.7,5.3,37.1,2.7c31.3-2.8,40.7,20.5,49.8,46.6c10.3,29.4,11.3,62.2,22.8,91
        c15.2,37.9,36.4,28.1,59,2.6c19.5-22,69-138.5,97.6-69.9c12.2,29.2,22.7,52.7,49.3,72.6c26.5,19.8,45.2-7.6,63.5-29.2"/>
  
<path pathLength='1' id='chemin' d="M3.1,53.4C3.3,42.1,4.2,30,9.8,19.9C16,8.6,27.5,3.6,40,3.2c11.8-0.4,22.6,3.7,30.2,12.9c7.4,8.9,11.4,20.2,15.2,30.9
                    C95.8,76.3,97,108,107.9,137.2c3.6,9.7,8.6,21.5,18.3,26.7c6.7,3.6,14.3,2.2,20.8-1.3c14.3-7.7,24.6-21.2,33-34.8
                    c8.9-14.4,17.3-29.1,27-43.1c7.9-11.4,18.2-26.8,32.1-31.5c17.3-5.8,24.9,16.1,30,28c10.1,23.7,22.3,45.9,42.8,62.3
                    c8.3,6.7,17.9,11.7,28.8,8.5c10.8-3.2,19.2-12.2,26.4-20.4c4.2-4.8,8.3-9.9,12.4-14.8c0.5-0.6-0.4-1.5-0.9-0.9
                    c-8.5,10.1-16.6,21.4-27.4,29.3c-12.1,8.8-24.7,7.9-36.5-1.1c-22.7-17.4-35.4-41.8-46.2-67.6c-4.5-10.7-11.5-27.1-25.8-25.4
                    C230,52.6,220,65.4,212.8,74.6c-10.7,13.8-19.5,28.8-28.5,43.7c-8.5,14.1-16.9,27.3-29.9,37.8c-7.9,6.3-18.6,12.1-28.4,6.2
                    c-11.9-7.1-16.9-23.9-20.5-36.3c-4.5-15.4-6.9-31.2-10.1-46.9C92.4,64.8,88.5,51,83.2,37.4C75.9,18.9,64.6,2.3,42.9,1.9
                    c-10.3-0.2-21.1,2.4-28.6,9.8C7.5,18.5,4.5,28,3.1,37.2C2.2,42.6,2,48,1.9,53.4C1.9,54.2,3.1,54.2,3.1,53.4L3.1,53.4z"/>


</svg>

对完整工作片段有任何想法吗?

0 个答案:

没有答案
相关问题