用后续计算累计填充svg

时间:2019-08-25 14:28:14

标签: javascript html dom svg

我正在尝试用新计算的商来填充我的svg(累积地 )。

这是我的HTML的一部分:

<div style='text-align:center;'>
    <svg width="100%" viewbox="0 0 30 42">
        <linearGradient id="lg" x1="0.5" y1="1" x2="0.5" y2="0">
            <stop stop-color="#61A4FF" offset="0%" id="progress"/>
            <stop stop-color="#FFFFFF" offset="0%" id="F1gst2"/>
            <!-- <stop offset="0%" stop-opacity="1" stop-color="#61A4FF"/>
                <animate attributeName="offset" values="0;1;0" repeatCount="indefinite" dur="10s" begin="0s"/>
            </stop>
            <stop offset="40%" stop-opacity="0" stop-color="#61A4FF">
                <animate attributeName="offset" values="0;1;0" repeatCount="indefinite" dur="10s"  begin="0s"/>
            </stop> -->
        </linearGradient>
        <path id='tear' fill="url(#lg)" stroke="black" stroke-width="1.0"
            d=" M  15 3
                Q  16.5 6.8 25 18
                A  12.8 12.8 0 1 1 5 18
                Q  13.5 6.8 15 3z   " />
    </svg>
</div>

还有我的JavaScript:

function calculate(){
  var numerator = document.getElementById('progressInput').value;
  var denominator = document.getElementById('goalInput').value;
  var quotient = parseFloat(numerator)/parseFloat(denominator);
  progressFill.setAttribute('offset', quotient);
};

基本上,每次我在输入字段中输入新值时,此代码都会刷新计算。第一次计算商数是很好的做法,但是我希望它累加后续的计算值(并且实际上是累计svg区域)。这可能吗?

例如,假设我首先计算parseFloat(numerator)/ parseFloat(denominator)为2/10,则svg会在第一次单击时填充形状的20%。如果要在此基础上再添加40%(所以parseFloat(numerator)/ parseFloat(denominator)另外4/10),如何将其定义为代码的补充?

我以为我可能不得不写一个if-then语句,该语句是我开始的(但是我很确定这是错误的):

function calculate(){
  var numerator = document.getElementById('progressInput').value;
  var denominator = document.getElementById('goalInput').value;
  var quotient = parseFloat(numerator)/parseFloat(denominator);
  if (document.getElementById('progress').offset="0%") {
    progressFill.setAttribute('offset', quotient);
  };
};

1 个答案:

答案 0 :(得分:0)

您尚未提供progressInput或GoalInput,因此我跳过了这些内容并使用了一个常量。每次单击按钮时,填充都会发生10%的变化,尽管方法是查询DOM以获取当前填充,然后再向其中添加10%。

function calculate(){
  var quotient = 0.1;
  document.getElementById("progress").offset.baseVal += quotient;
};
<div style='text-align:center;'>
<button class="button" class="accumulate" onclick="calculate()">Change</button>

<svg width="100%" viewbox="0 0 30 42">
        <linearGradient id="lg" x1="0.5" y1="1" x2="0.5" y2="0">
            <stop stop-color="#61A4FF" offset="0%" id="progress"/>
            <stop stop-color="#FFFFFF" offset="0%" id="F1gst2"/>
        </linearGradient>
        <path id='tear' fill="url(#lg)" stroke="black" stroke-width="1.0"
            d=" M  15 3
                Q  16.5 6.8 25 18
                A  12.8 12.8 0 1 1 5 18
                Q  13.5 6.8 15 3z   " />
    </svg>
</div>