Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give a polygon a gradient fill inside a svg?

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

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.

Here is the raw HTML before the plugin converts it:

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

Here is the chart after the conversion:

<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>

What I have tried:

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.

HERE IS A DEMO

like image 224
Fizzix Avatar asked May 05 '14 02:05

Fizzix


1 Answers

Use an SVG gradient.

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>

Then refer to it in your CSS:

polygon {
    fill: url(#grad);
}

Demo here

You can learn more about SVG gradients here:

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

like image 163
Paul LeBeau Avatar answered Oct 18 '22 09:10

Paul LeBeau