如何在svg中为多边形提供渐变填充? [英] How to give a polygon a gradient fill inside a svg?

查看:443
本文介绍了如何在svg中为多边形提供渐变填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个非常棒的jQuery插件 - http://benpickles.github.io/peity/

I am using this awesome jQuery plugin - http://benpickles.github.io/peity/

基本上,它以 svg 格式呈现迷你图形和图表。在此 svg 元素中,有一个多边形和一个折线。我需要能够给多边形一个渐变作为填充,而不是纯色。

Basically, it renders mini graphs and charts in svg format. Within this svg element, there is one polygon and one polyline. I need to be able to give the polygon a gradient as its fill, instead of a solid colour.

这是插件转换之前的原始HTML:

<td class="chartSection">
    <span class="chart">100, 100.67, 102.34, 109.30, 101.20, 99.20, 70.20</span>
</td>

以下是转换后的图表:

<td class="chartSection">
    <span class="chart" style="display: none;">100, 100.67, 102.34, 109.30, 101.20, 99.20, 70.20</span>
    <svg class="peity" height="53" width="200">
        <polygon fill="#c6d9fd" points="0 52 0 4.924519670631284 33.333333333333336 4.6057639524245175 66.66666666666667 3.8112534309240544 100 0.5 133.33333333333334 4.353613906678859 166.66666666666669 5.305123513266238 200 19.102012808783165 200 52"></polygon>
        <polyline fill="transparent" points="0 4.924519670631284 33.333333333333336 4.6057639524245175 66.66666666666667 3.8112534309240544 100 0.5 133.33333333333334 4.353613906678859 166.66666666666669 5.305123513266238 200 19.102012808783165" stroke="#4d89f9" stroke-width="1" stroke-linecap="square"></polyline>
    </svg>
</td>

我尝试了什么:

我尝试通过CSS给出 fill 渐​​变,例如 fill:linear-gradient(#FF0000,#00FF71)。虽然,这导致填充为纯黑色。

I attempted to give the fill a gradient through CSS such as fill: linear-gradient(#FF0000, #00FF71). Although, this caused the fill to be a solid black.

这里是一个演示

推荐答案

使用SVG渐变。

在HTML文件中将渐变定义添加为单独的SVG片段:

Add the gradient definition as a separate snippet of SVG in your HTML file:

<span class="chart">100, 100.67, 102.34, 109.30, 101.20, 99.20, 70.20</span>

<svg>
    <defs>
        <linearGradient id="grad">
            <stop offset="0" stop-color="red"/>
            <stop offset="1" stop-color="blue"/>
        </linearGradient>
    </defs>
</svg>

然后在CSS中引用它:

Then refer to it in your CSS:

polygon {
    fill: url(#grad);
}

在这里演示

您可以在此处了解有关SVG渐变的更多信息:

You can learn more about SVG gradients here:

http://www.w3.org/TR/SVG11/pservers.html

这篇关于如何在svg中为多边形提供渐变填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆