SVG用不同的颜色绘制路径的不同部分

时间:2019-01-17 00:49:19

标签: javascript html5 svg snap.svg

I have been trying to implement the following requirements.
 1. SVG path to have multiple colors on different sections (eg - red color the curves and rest of it, in black color)
 2. Only allow mouse event- click on those colored areas (curves)

I have tried with plain javascript and snap.svg

    Plain html & Javascript
   [Codepen using HTML & Js][1]
    SNAP.svg
   [Codepen using SNAP.svg][2]


   [1]: https://codepen.io/sanathko1234/pen/vvMQQZ
   [2]: https://codepen.io/sanathko1234/pen/OrGoRa

How can this be achieved? 

1 个答案:

答案 0 :(得分:1)

一种解决方案是使用两次路径:首先使用绿色,然后使用stroke-dasharray。破折号仅在曲线上方。如果您不喜欢破折号的位置或长度,请将其更改为所需的值。间隙对鼠标事件不敏感,仅对破折号敏感。

在CSS中,我添加了#gold:hover{cursor:pointer},以便您可以看到只有破折号对鼠标敏感。

我希望它会有所帮助。

svg{border:1px solid}
use{fill:none;stroke-width:18;}
#gold:hover{cursor:pointer}
<svg viewBox="-10 50 580 360" width="580" height="360" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <path id="svg_1" d="m555,272c1,0.76736 4,85.76736 -71,97.76736c-75,12 -387,-39 -388,-39.76736c0,-0.23264 -29,-1.23264 -45,-21.23264l-42,-124.76736c-3,-11.23264 -3,-21.23264 3,-26.23264c6,-5 46,-67 69,-69.76736l474,184z" />
  </defs>
 <g>
  <title>background</title>
  <rect fill="#fff" id="canvas_background" height="360" width="580" x="-10" y="50"/>
 </g>
 <g>
  <title>Layer 1</title>
  
<use xlink:href="#svg_1" stroke="green"  />   
<use xlink:href="#svg_1" stroke="gold" stroke-dasharray ="130 370 110 60 90 40 90 400 52.45" id="gold" pointer-events="stroke" />
 </g>
</svg>

观察:破折号和间隙之和为1342.45,这也是总路径长度。