简体   繁体   中英

SVG Filter: width 100% height 100% does not cover image

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>

Hardcoding the filter to have a width of 200px and a height of 200px works

 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='200px' height='200px'> <feGaussianBlur stdDeviation='2' result='blur' /> </filter> <image x='0' width='200px' height='200px' xlink:href='' id='svg-image' filter='url(#blur)' /> </svg>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM