I have a simple SVG Filter. If you click the example below, that filter will appear/disappear:
var image = document.querySelector('image');
var url = 'https://i.picsum.photos/id/202/200/200.jpg?hmac=eGzhW5P2k0gzjc76Tk5T9lOfvn30h3YHuw5jGnBUY4Y';
image.setAttribute('xlink:href', url);
window.addEventListener('click', function() {
var filter = image.getAttribute('filter')
? ''
: 'url(#blur)';
image.setAttribute('filter', filter);
})
image {
background: red;
}
<svg width='200' height='200'>
<filter id='blur' width='100%' height='100%'>
<feGaussianBlur stdDeviation='2' result='blur' />
</filter>
<image x='0' width='200px' height='200px' xlink:href='' id='svg-image' filter='url(#blur)' />
</svg>
I'd like the filtered image to be the same size as the unfiltered image. Does anyone know how I can accomplish this? Any pointers would be appreciated!
You need to set the initial dimension using x
and y
attribute as follows.
<filter id='blur' x='0' y='0' width='100%' height='100%'>
...
var image = document.querySelector('image');
var url = 'https://i.picsum.photos/id/202/200/200.jpg?hmac=eGzhW5P2k0gzjc76Tk5T9lOfvn30h3YHuw5jGnBUY4Y';
image.setAttribute('xlink:href', url);
window.addEventListener('click', function() {
var filter = image.getAttribute('filter')
? ''
: 'url(#blur)';
image.setAttribute('filter', filter);
})
image {
background: red;
}
<svg width='200' height='200'>
<filter id='blur' x='0' y='0' width='100%' height='100%'>
<feGaussianBlur stdDeviation='2' result='blur' />
</filter>
<image x='0' width='200px' height='200px' xlink:href='' id='svg-image' filter='url(#blur)' />
</svg>