Add drop-shadow to SVG element programmatically

Viewed 187

I am using JavaScript to add circles to inline SVG. How can I style those circles to include a drop-shadow effect?

I found the drop-shadow() CSS function but apparently it doesn't apply to individual SVG elements.

I also found the SVG filter element and how it can be included manually in the code under defs. But in my case the SVG is retrieved at runtime and I need to add the shadow programmatically.

<filter id="shadow">
  <feDropShadow dx="0.2" dy="0.4" stdDeviation="0.2"/>
</filter>

[update] I am almost there. What I don't understand is why my shadow is cropped to fit in a square. cropped shadow

My code:

// Add the drop-shadow effect
let defs = document.createElementNS(NS, 'defs');
let filter = document.createElementNS(NS, 'filter');
filter.setAttribute("id", "dropshadow");

let feDropShadow = document.createElementNS(NS, 'feDropShadow');
feDropShadow.setAttribute("dx", "0");
feDropShadow.setAttribute("dy", "0");
feDropShadow.setAttribute("stdDeviation", "2");

draw.appendChild(defs);
defs.appendChild(filter);
filter.appendChild(feDropShadow);
0 Answers
Related