多个多边形的相同渐变变化 - SVG

Same Gradient vary for multiple polygons - SVG

我正在使用将多边形附加到 SVG 文件的脚本创建多座山。

我可以定义多边形应该使用多少百分比的渐变吗?或者有更好的方法吗

这将是我的 mountains.js,它获得分数并附加它。

$(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 + '" />');
}});});

这是我的 SVG 文件。

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

目前,您的渐变设置 gradientUnits="userSpaceOnUse"。这意味着您为渐变向量定义的百分比是相对于视口的。如果您改为设置 gradientUnits="objectBoundingBox",则百分比将相对于引用元素的边界框和

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

将定义一个从边界框左上角到左下角的梯度向量 运行。我认为你所说的 "how much % the polygons should use from the Gradient".

是什么意思

您甚至可以保留 gradientUnits 属性,因为 objectBoundingBox 是默认值。