Search code examples
javascripthtmlsvgsnap.svg

SVG make different sections of the path in different colors


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? 

Solution

  • One solution would be to use the path twice: first the green one and next the one using stroke-dasharray. The dashes are only over the curves. If you don't like the position or the length of the dashes change them to what you need. The gaps are not sensitive to mouse events, only the dashes are.

    In css I've added #gold:hover{cursor:pointer} so that you can see that only the dashes are sensitive to the mouse.

    I hope it helps.

    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>

    Observation: the sum of the dashes and the gaps is 1342.45 which is also the total path length.