如何在d3和SVG中创建阴影路径?

时间:2015-01-07 20:22:36

标签: javascript svg d3.js

我正在创建一个带着阴影效果的图表,并且希望有一个效果类似于this的效果图,来自Apple的健康套件,除了在最后一个数据点之后没有尖锐的垂直线。基本上我想要阴影线下面的线条形状,而不是像一个非常模糊的阴影。怎么能在d3中实现呢?

1 个答案:

答案 0 :(得分:2)

除了图形线之外,您还需要创建一个放在线后面的多边形。为该多边形赋予线性渐变。渐变色为白色,从顶部半透明到底部完全透明。

下面的演示。我会让你把它转换成d3。

    <svg width="750" height="384">
      <defs>
        <!-- The below-the-graph gradient fill -->
        <linearGradient id="grad" x2="0" y2="1">
          <stop offset="0%" stop-color="white" stop-opacity="0.5"/>
          <stop offset="100%" stop-color="white" stop-opacity="0"/>
        </linearGradient>

        <filter id="blur">
          <feGaussianBlur stdDeviation="10" />
        </filter>
      </defs>

      <!-- The orange background -->
      <rect x="10" y="10" width="734" height="368" rx="14" fill="#ff7744"/>

      <!-- This transform just moves the graph from the origin (top left) onto the orange background -->
      <g transform="translate(80,134)">

        <!-- Same shape as the graph but adds points at bottom right and bottom left to complete the polygon -->
        <polygon fill="url(#grad)" filter="url(#blur)"
                 points="0,127, 90,85, 180,115, 270,47, 360,143, 450,0
                         450,177, 0,177"/>

        <!-- The white graph line goes last (on top) -->
        <polyline fill="none" stroke="white" stroke-width="3"
                  points="0,127, 90,85, 180,115, 270,47, 360,143, 450,0"/>
      </g>
      
    </svg>

<强>更新

抱歉,我一定错过了关于模糊线下渐变的观点。我在我的示例中添加了一些模糊,以向您展示模糊滤镜可以执行的操作。这只是一个快速的黑客,你可以看到它如何在线上流血。要解决这个问题,你需要制作一个遮罩或剪辑路径来遮挡线条上方的区域,这样就不会看到出血。