BlueScoreMan
BlueScoreMan

Reputation: 707

Same Gradient vary for multiple polygons - SVG

I am creating multiple mountains using a script which appends the polygons to the SVG file.

Can I define how much % the polygons should use from the Gradient? Or is there a better way to do this.

This would be my mountains.js which gets the points and appends it.

$(function () {
$.getJSON('../data/mountains-points.json', function (data) {
    for (let layer of data) {
        let result = '';
        for (let point of layer.path) {
            result += point.x + ',' + point.y + ' ';
        }
        $('#mountains').append('<polygon style="stroke:black;stroke-width:10;" fill="url(#black_white)" class="mountains" xmlns="http://www.w3.org/2000/svg" points="' + result + '" />');
}});});

This is my SVG file.

<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="100%"
 height="100%" xmlns="http://www.w3.org/2000/svg"
 version="1.1">
<script type="text/javascript" xlink:href="../libs/jquery-3.3.1.min.js"/>
<script type="text/javascript" xlink:href="../js/mountains.js"/>

<defs>
    <linearGradient id="black_white" x1="0%" y1="0%" x2="0%" y2="100%" gradientUnits="userSpaceOnUse">
        <stop offset="0%" style="stop-color:rgb(0,0,0);stop-opacity:1"/>
        <stop offset="100%" style="stop-color:rgb(255,255,255);stop-opacity:1"/>
    </linearGradient>
</defs>

<g id="mountains">

</g>

</svg>

Upvotes: 1

Views: 102

Answers (1)

ccprog
ccprog

Reputation: 21821

Currently, your gradient sets gradientUnits="userSpaceOnUse". That means the percentages you define for the gradient vector are relative to the viewport. If you set gradientUnits="objectBoundingBox" instead, the percentages would be relative to the bounding box of the referencing element and

<linearGradient id="black_white" x1="0%" y1="0%" x2="0%" y2="100%"
                gradientUnits="objectBoundingBox">

would define a gradient vector running from the top left corner of the bounding box to the bottem left corner. I think that what you mean by "how much % the polygons should use from the Gradient".

You can even leave of the gradientUnits attribute, as objectBoundingBox is the default value.

Upvotes: 1

Related Questions