javascript 用多种颜色填充 SVG 路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29335354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:23:50  来源:igfitidea点击:

Filling an SVG path with multiple colors

javascriptcsssvg

提问by eatplayrove

I have a map of provinces of a country as an SVG, where each province is an SVG path. The actual SVG is the following province map.

我有一个国家的省份地图作为 SVG,其中每个省都是一个 SVG 路径。实际的SVG是以下省地图

What I would like to do is fill a part of the province (the path) with one color, a second part with another, and the rest with another color. So for example I would have 33.33% percent of the path on the x-axis filled with color a, from 33.33 to 66.66% with color b, and the rest with color c.

我想做的是用一种颜色填充省(路径)的一部分,用另一种颜色填充第二部分,用另一种颜色填充其余部分。例如,我将 x 轴上 33.33% 的路径用颜色 a 填充,从 33.33 到 66.66% 用颜色 b,其余的用颜色 c。

Is this possible? I have seen linear gradients, but rather than a gradient I would like to have solid colors.

这可能吗?我见过线性渐变,但我想要纯色而不是渐变。

Thanks!

谢谢!

回答by torox

I think you would be able to use a linear gradient and use two color-stops for each solid color. Something like this

我认为您可以使用线性渐变并为每种纯色使用两个色标。像这样的东西

<svg height="200" width="600">
  <defs>
    <linearGradient id="solids" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
      <stop offset="33%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
      <stop offset="33%" style="stop-color:rgb(0,255,0);stop-opacity:1" />
      <stop offset="67%" style="stop-color:rgb(0,255,0);stop-opacity:1" />
      <stop offset="67%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
      <stop offset="100%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
    </linearGradient>
  </defs>
  <rect width="600" height="200" fill="url(#solids)" />
</svg>

回答by Michael Mullany

It is not possible to do this directly in general (gradients and filters allow you to fill a path with very customized fills but it can get extremely difficult to calculate the right gradient).

通常无法直接执行此操作(渐变和过滤器允许您使用非常自定义的填充填充路径,但计算正确的渐变会变得非常困难)。

The easiest way to do this is to draw the path several times, with different colors and customized stroke-dash-array's.

最简单的方法是多次绘制路径,使用不同的颜色和自定义笔划-破折号数组。