如何在 d3 和 SVG 中创建着色路径

How to create shaded path in d3 and SVG?

本文关键字:创建 路径 SVG d3      更新时间:2023-09-26

我正在创建一个带有阴影效果的图表,并希望有一个折线图,其效果类似于Apple的健康工具包中的这个,除了最后一个数据点之后没有清晰的垂直线。本质上,我希望在线条下方进行阴影,该线条的形状,就像一个非常模糊的阴影。如何在 d3 中实现这一点?

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

下面的演示。 我会让你把它转换为 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>

更新

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