Search code examples
javascriptsvgpolylinesvg-filters

How to create a svg line with a filter


I would like to create lines with the following effect :

line sample

The above was created with the following :

<svg id="svg_wrp" width="500" height="500">
    <defs>
         <filter id="crayon">
            <feTurbulence
                type="fractalNoise"
                baseFrequency="1.001"
                numOctaves="10"
                result="noise">
            </feTurbulence>
            <feDisplacementMap
                xChannelSelector="R"
                yChannelSelector="G"
                scale="50"
                in="SourceGraphic"
                result="newSource">
            </feDisplacementMap>
      <feGaussianBlur stdDeviation="1.1"/>
        </filter>
 </defs>
  <polyline    
  points="200,100 100,200"
  stroke="#000"
  stroke-width="10"
  fill="none"
  filter=url(#crayon) ></polyline>
</svg>

Above in Fiddle

This method does not work for much of what I want to do. The effect changes depending on the length and direction of the line.

The only way I can think of doing this is by replacing all the lines with polygons. Then it would be a straight forward use of filters. But then I would have to create a complex polygon with all the calculations for each corner and curve.

So before I do that I would like to know if there is a way to achieve the above with svg polylines or some other method.

Edit: Michael Mullany's answer solved the vertical and horizontal only line issue, but I still have problems with the effect differing on some lines, see below for an example. Notice effect is reduced in top left. Is there a way to have a consistent effect on all lines?

enter image description here


Solution

  • Default filter dimensions don't work on horizontal and vertical lines because they have a zero area bounding box. You need to change your filter units to:

    <filter id="crayon" filterUnits="userSpaceOnUse" x="0" y="0" width="500" height="500">
    

    Otherwise this filter is fine.

    Update: there are some values for baseFrequency that cause anomalies/moire-like artifacts - apparently 1.001 is one of them for this case. If you tweak that baseFrequency down to 0.98, the problem disappears.