嵌入JavaScript时SVG过滤器无法正常工作

时间:2016-06-16 16:56:18

标签: javascript css svg

我一直在努力让模糊效果在创建元素并使用JavaScript嵌入它们时起作用。我无法弄清楚为什么模糊不会出现。我有两个小提琴,一个是标准的HTML& CSS和另一个使用JavaScript。如果有人想要检查出来并提供我正在做错的解释,我会非常感激。

HTML& CSS版本(Works) https://jsfiddle.net/aaronbalthaser/xampLtnr/

HTML:

<div id="container">
  <img src="http://lorempixel.com/300/250/sports/" width="300" height="250" />
  <svg width="300" height="60" viewbox="0 0 300 60">
    <defs>
      <filter id="blur">
        <fegaussianblur in="SourceGraphic" stddeviation="5" />
      </filter>
    </defs>
    <image filter="url(#blur)" xlink:href="http://lorempixel.com/300/250/sports/" x="0" y="-190" height="250px" width="300px" />
  </svg>
</div>

CSS:

#container {
  position: relative;
  width: 300px;
  height: 250px;
  margin: 0 auto;
  position: relative;
}

svg {
  position: absolute;
  bottom: 0;
  left: 0;
}

JavaScript版本(不起作用) https://jsfiddle.net/aaronbalthaser/Lbnkfn02/

HTML:

<div id="container">
  <img src="http://lorempixel.com/300/250/sports/" width="300" height="250" />


</div>

CSS:

#container {
  position: relative;
  width: 300px;
  height: 250px;
  margin: 0 auto;
  position: relative;
}

svg {
  position: absolute;
  bottom: 0;
  left: 0;
}

JS:

var width = 300;
var height = 250;
var viewbox = "0 0 300 60";
var namespace = 'http://www.w3.org/2000/svg'
var path = 'http://lorempixel.com/300/250/sports/';
var container = document.getElementById('container');
var body = document.body;

var svg = document.createElementNS(namespace,'svg');
svg.setAttribute('width', width);
svg.setAttribute('height', 60);
svg.setAttribute('viewBox', viewbox);

var defs = document.createElementNS(namespace, 'defs');
var filter = document.createElementNS(namespace, 'filter');
filter.setAttribute('id', 'blur');

var feGaussianBlur = document.createElementNS(namespace, 'feGaussianBlur');
feGaussianBlur.setAttribute('in', 'SourceGraphic');
feGaussianBlur.setAttribute('stdDeviation', '5');

var image = document.createElementNS('http://www.w3.org/2000/svg', 'image');
image.setAttribute('filter', 'url(#blur)');
image.setAttribute('xlink:href', path);
image.setAttribute('x', + '0');
image.setAttribute('y', + '-190');
image.setAttribute('height', height + 'px');
image.setAttribute('width', width + 'px');

filter.appendChild(feGaussianBlur);
defs.appendChild(filter);
svg.appendChild(defs);
svg.appendChild(image);
container.appendChild(svg);

console.log(container);

1 个答案:

答案 0 :(得分:2)

image.setAttribute('xlink:href', path);

应该是

image.setAttributeNS("http://www.w3.org/1999/xlink", 'xlink:href', path);

https://jsfiddle.net/Lbnkfn02/2/