Smek
Smek

Reputation: 1208

Add filter to SVG dynamically

I have the following SVG image inline on a webpage:

const svg = document.getElementById('svg');
const filter = document.createElementNS('http://www.w3.org/2000/svg', 'filter');
filter.setAttribute('id', 'image');
filter.setAttribute('x', '0%');
filter.setAttribute('y', '0%');
filter.setAttribute('width', '100%');
filter.setAttribute('height', '100%');
const feImage = document.createElementNS('http://www.w3.org/2000/svg', 'feImage');
feImage.setAttribute('xlink:href', 'http://lorempixel.com/100/100/');
filter.appendChild(feImage);
svg.querySelector('defs').appendChild(filter);
svg.querySelector('circle').setAttribute('filter', 'url(#image)');
<svg width="200" height="200" viewBox="0 0 200 200" id="svg">
<defs></defs>
<circle cx="100" cy="100" r="50" fill="none" stroke-width="2" stroke="gray"></circle>
</svg>

Now I would like to add an image filter to this svg dynamically and then apply the filter to the circle. But what happens is the circle becomes invisible the filter does not work.

When I add the filter to the svg hardcoded everything works just fine:

<svg width="200" height="200" viewBox="0 0 200 200" id="svg">
        <defs>
            <filter id="image" x="0%" y="0%" width="100%" height="100%">
                <feImage xlink:href="http://lorempixel.com/100/100/"></feImage>
            </filter>
        </defs>
        <circle cx="100" cy="100" r="50" fill="none" stroke-width="2" stroke="gray" filter="url(#image)"></circle>
</svg>

My question is why doesn't this work?

Upvotes: 1

Views: 394

Answers (1)

philipp
philipp

Reputation: 16515

You need to use: document.createElementNS(…) for svg elements and in this case setAttributeNS(…) as well;

For instance change:

 const filter = document.createElement('filter');

to

 const filter = document.createElementNS('http://www.w3.org/2000/svg', 'filter');

Additionally change:

feImage.setAttribute('xlink:href', 'http://lorempixel.com/100/100/');

to

feImage.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'http://lorempixel.com/100/100/');

fiddle

Upvotes: 3

Related Questions