使用 d3 在点击时将 svg:image 转换为灰度

Emi*_*Chu 2 javascript css svg image d3.js

有问题的网站

我正在尝试使用以下功能将使用 d3.select 附加的所有 svg:images 转换为灰度:

js:

 <script>

  function convert() {
    d3.selectAll("image")
      .style('filter', 'grayscale(100%)');
  }

</script>
Run Code Online (Sandbox Code Playgroud)

html:

<label id="label" style="display:inline;cursor:pointer;" onclick="convert();">
See in Grayscale</label>
Run Code Online (Sandbox Code Playgroud)

有问题的目标项目是通过以下方式创建的:

  var images = nodeEnter.append("svg:image")
    .attr("xlink:href",  function(d) { return d.path;})
    .attr("x", function(d) { return -25;})
    .attr("y", function(d) { return -25;})
    .attr("height", 50)
    .attr("width", 50);
Run Code Online (Sandbox Code Playgroud)

我看到检查器中的功能将样式属性过滤器添加到灰度 100%,但元素没有变成灰度。

有任何想法吗?

Gil*_*sha 5

由于您使用的是 SVG 图像而不是<img>标签,您应该应用过滤器,如下面的代码片段所示。

var nodes = [{
  path: "https://images.pexels.com/photos/459225/pexels-photo-459225.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
  x: 0,
  y: 20
}, {
  path: "https://images.pexels.com/photos/223022/pexels-photo-223022.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
  x: 250,
  y: 20
}];

var nodeEnter = d3.select("svg")
  .selectAll("node")
  .data(nodes)
  .enter()
  .append("g")
  .attr("transform", function(d) {
    return "translate(" + d.x + "," + d.y + ")";
  });

nodeEnter.append("rect")
  .attr("x", 0)
  .attr("y", 0)
  .attr("height", 200)
  .attr("width", 200);

nodeEnter.append("svg:image")
  .attr("xlink:href", function(d) {
    return d.path;
  })
  .attr("x", 0)
  .attr("y", 0)
  .attr("height", 200)
  .attr("width", 200);

function convert() {
  d3.selectAll("image")
    .style('filter', 'url(#grayscale)');
}
Run Code Online (Sandbox Code Playgroud)
label {
  position: absolute;
  top: 0;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v3.min.js"></script>
<label id="label" style="display:inline;cursor:pointer;" onclick="convert();">
See in Grayscale</label>

<svg x=0 y=0 width=500 height=500>
 <filter id="grayscale">
  <feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0"/>
 </filter>
</svg>
Run Code Online (Sandbox Code Playgroud)