D3js SVG重叠:具有许多随机形状的SVG的自定义颜色

时间:2018-08-24 23:52:53

标签: javascript jquery css d3.js svg

我需要完成图像中显示的颜色“混合”-对于重叠2种形状的区域,它需要显示为特定颜色(此处为橙色),而单独显示3种重叠的颜色(此处为红色) 。

我需要一些非常动态且易于扩展到更多重叠形状的东西。在各个区域中最多可能有20种形状重叠。形状是随机的,没有可预测的形式。

我正在使用D3js将形状绘制为SVG多边形。

我已经尝试过css mix-blend-mode ,但这对我的需求没有用。我已经研究了两天了,没有运气...

enter image description here

1 个答案:

答案 0 :(得分:1)

如果mix-blend-mode不能满足您的需求(也许您不喜欢颜色或未将isolation: isolate;应用于组),则可以尝试使用clipPath

由于您不发布代码,因此无法处理您的示例。接下来的代码可能会给您一些想法。

<svg xmlns="http://www.w3.org/2000/svg" xml:lang="en"
xmlns:xlink="http://www.w3.org/1999/xlink"
height="360px" width="360px" viewBox="-18 -12.5 36 36">
<title>Venn Diagram</title>
<style>
.left { fill: #1dd0b8; }
.right { fill: #47ef96; }
.circle{ fill: #b147ef; }
.outlines {
fill: none;
stroke: black;
}
</style>
<defs>
<circle id="c" r="11.5" />
<use id="left" xlink:href="#c" x="-6"/>
<use id="right" xlink:href="#c" x="6"/>
<use id="circle" xlink:href="#c" y="10"/> 

<clipPath id="clip-left">
  <use xlink:href="#c" x="-6" />
</clipPath>
  
<clipPath id="clip-right">
  <use xlink:href="#c" x="+6" />
</clipPath> 
  
<clipPath id="clip-both" clip-path="url(#clip-left)">
<defs>a clipPath element can have a clip-path
applied to it.</defs>
<use xlink:href="#c" x="6" />
</clipPath> 
</defs>
  
<use xlink:href="#left" class="left" />
<use xlink:href="#right" class="right" />
<use xlink:href="#circle" class="circle" />

<g clip-path="url(#clip-left)">
<use xlink:href="#c" x="+6" fill="#e89f0c" />
</g>
<g clip-path="url(#clip-right)">
<use xlink:href="#c" x="0" y="10" fill="#e89f0c" />
</g> 
<g clip-path="url(#clip-left)">
<use xlink:href="#c" y="10" fill="yellow" />
</g> 
  
<g clip-path="url(#clip-both)">
<use xlink:href="#c" y="10" fill="red" />
</g>
  
    
<g class="outlines">
<use xlink:href="#left" />
<use xlink:href="#right" />
<use xlink:href="#circle" />
</g>
</svg>

上面的示例在很大程度上受Using SVG with CSS3 and HTML5: Vector Graphics for Web Design

中的“剪切clipPath”的启发