2017-08-08 121 views
3

我想为我使用d3和SVG绘制的阴影设置阴影,但我在叠加相邻元素的阴影时遇到了问题。看到下面的图片,了解它目前的样子。请注意,中间的六边形看起来有不同的高度,因为阴影正在其中一些上面呈现。我想要做的就是设置阴影,使它们只在背景上渲染,而不是在其他相邻的格子上。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"); 

的样式会应用到六边形:

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

Shadows overlapping hexagaons

回答

3

你并不需要创建一个一大堆两层重复。你所需要做的就是将所有的六边形包装在一个组中(<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>

-2

enter image description here我有找出一个临时解决方案。从本质上讲,它涉及到创建两套不同的层上六边形的:

  1. 没有填充/笔触底层在一组,但与顶层上所有的填充/笔触的阴影
  2. 一组,但没有阴影

由于#2#1以上,影子将不会在任何可见六边形的顶部显示...