如何只填充SVG的一部分? [英] How to fill only a part of the SVG?

查看:37
本文介绍了如何只填充SVG的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将数字/百分比传递给填充 svg 一部分的函数.例如,在一个桶的 svg 中,如果现实生活中的桶被填充了 90% 并且它返回 10 升作为整数,我希望我网站上的桶 svg 用蓝色填充 90%.

I want to be able to pass a number/percentage to a function that fills a part of an svg. For example in an svg of a bucket if the real life bucket is filled 90% of the way and it returns 10 liters as an integer I want the bucket svg on my website to be filled 90% of the way with blue.

我相信您可以将 SVG 分成带有 ID 的部分,并根据函数传递的数字填充每个 ID,然后使用某种 jquery 函数编辑每个部分?但是,我觉得只填充 SVG 的一部分肯定是更受欢迎的事情,但是我找不到一种直接/简单的方法来做到这一点?

I believe you can portion an SVG into parts with an ID and fill each ID based on the number the function is passed and then edit each part with some kind of jquery function? However, I feel like filling only part of an SVG must be a more popular thing to do but I haven't been able to find a straightforward/simple way of doing this?

推荐答案

最简单的方法是使用 .

The simplest way to do this is with a <linearGradient>.

function setWaterLevel(percent)
{
  document.getElementById("stop1").setAttribute("offset", percent+"%");
  document.getElementById("stop2").setAttribute("offset", percent+"%");
}


document.getElementById("slider").addEventListener("input", function(evt) {
  setWaterLevel(evt.target.value);
});

setWaterLevel(0);

<svg width="300px" viewBox="0 0 100 100">
  <defs>
    <linearGradient id="water" x1="0" y1="1" x2="0" y2="0">
      <stop id="stop1" offset="0%" stop-color="blue"/>
      <stop id="stop2" offset="0%" stop-color="transparent"/>
    </linearGradient>
  </defs>

  <polygon points="0,0, 100,0, 80,100, 20,100"
           fill="url(#water)" stroke="black"/>
</svg>

<br>
<input id="slider" type="range" min="0" max="100" step="10" value="0"/>

这篇关于如何只填充SVG的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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