SVG阴影分层

jrd*_*dhl 4 javascript css svg d3.js

我想在使用d3和SVG制作的绘图中有阴影,但是阴影与相邻元素重叠会给我带来麻烦。有关当前外观,请参见下图。请注意,中间的六边形似乎具有变化的标高,因为在其中一些阴影上渲染了阴影。我想做的是设置阴影,使其仅在背景上渲染,而不在其他相邻的十六进制上渲染。

这是当前如何定义阴影的代码:

      var filter = defs.append("filter")
        .attr("id", "drop-shadow")
        .attr("height", "130%");

    // SourceAlpha refers to opacity of graphic that this filter will be applied to
    // convolve that with a Gaussian with standard deviation 3 and store result
    // in blur
    filter.append("feGaussianBlur")
        .attr("in", "SourceAlpha")
        .attr("stdDeviation", 1)
        .attr("result", "blur");

    // translate output of Gaussian blur to the right and downwards with 2px
    // store result in offsetBlur
    filter.append("feOffset")
        .attr("in", "blur")
        .attr("dx", 1)
        .attr("dy", 1)
        .attr("result", "offsetBlur");

    // overlay original SourceGraphic over translated blurred opacity by using
    // feMerge filter. Order of specifying inputs is important!
    var feMerge = filter.append("feMerge");

    feMerge.append("feMergeNode")
        .attr("in", "offsetBlur")
    feMerge.append("feMergeNode")
        .attr("in", "SourceGraphic");
Run Code Online (Sandbox Code Playgroud)

然后将这些样式应用于六边形:

d3.select(this).style("filter", "url(#drop-shadow)")

阴影重叠的六面体

Pau*_*eau 5

您无需在两层中创建一堆重复项。您需要做的就是将所有六边形包裹在一个组(<g>)中,然后对其应用过滤器。

<svg>
  <defs>
    <filter id="drop-shadow" width="150%" height="150%">
      <feGaussianBlur in="SourceAlpha" stdDeviation="3" result="blur"/>
      <feOffset in="blur" dx="2" dy="2" result="offsetBlur"/>
      <feMerge>
        <feMergeNode in="offsetBlur"/>
        <feMergeNode in="SourceGraphic"/>
      </feMerge>
    </filter>
  </defs>

  <rect x="75" y="75" width="50" height="50" fill="cyan"
        filter="url(#drop-shadow)"/>
  <rect x="75" y="25" width="50" height="50" fill="gold"
        filter="url(#drop-shadow)"/>
  <rect x="25" y="75" width="50" height="50" fill="lime"
        filter="url(#drop-shadow)"/>
  <rect x="25" y="25" width="50" height="50" fill="red"
        filter="url(#drop-shadow)"/>

  <g filter="url(#drop-shadow)" transform="translate(150,0)">
    <rect x="75" y="75" width="50" height="50" fill="cyan"/>
    <rect x="75" y="25" width="50" height="50" fill="gold"/>
    <rect x="25" y="75" width="50" height="50" fill="lime"/>
    <rect x="25" y="25" width="50" height="50" fill="red"/>
  </g>
</svg>
Run Code Online (Sandbox Code Playgroud)