簡體   English   中英

SVG對象上的實時迭代

[英]Real-time Iteration over SVG objects

例如我在html中有這個

<svg id="svg-img1" width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <line x1="0" y1="0" x2="0" y2="0" style="stroke:black; stroke-width:1px;"></line>
    <line x1="0" y1="0" x2="0" y2="0" style="stroke:black; stroke-width:1px;"></line>
    <line x1="0" y1="0" x2="0" y2="0" style="stroke:black; stroke-width:1px;"></line>
    <line x1="0" y1="0" x2="0" y2="0" style="stroke:black; stroke-width:1px;">  </line>
</svg>

這在我的js中

$('svg').find('line').each(function(){
    $(this).attr('style','stroke:red');
    sleep(10);
});

和“睡眠”功能

function sleep(ms) {
  ms += new Date().getTime();
  while (new Date() < ms){}
} 

執行時,每個人的線條顏色都會立即改變。 我需要線條的顏色依次更改,以便可以將其視為一種顏色,另一種顏色會更改顏色。 類似於動畫

嘗試不使用jQuery-相同的結果

使用SVG動畫元素:

  <animate id="a14" attributeName="stroke" from="black" to="red" dur="3s" begin="9s;al4.end+3s" stroke="freeze" /> 

注意:請勿剪切並粘貼上面的代碼,因為該代碼已在中間斷開,因此無需滾動即可看到它。

  • attributeName :要設置動畫的屬性的名稱
  • from :起始值
  • toto
  • dur :動畫的持續時間
  • begin :何時開始; 這組特定的值表示:9秒內開始; (通過ID引用此動畫元素)在3秒內結束
  • stroke :正在動畫的屬性,該屬性在動畫后將停止,

SNIPPET

 <svg id="svg-img1" width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"> <line x1="0" y1="10" x2="400" y2="10" style="stroke:black; stroke-width:1px;"> <animate id="a11" attributeName="stroke" from="black" to="red" dur="3s" begin="0s;al1.end+3s" stroke="freeze" /> </line> <line x1="0" y1="20" x2="400" y2="20" style="stroke:black; stroke-width:1px;"> <animate id="a12" attributeName="stroke" from="=black" to="red" dur="3s" begin="3s;al2.end+3s" stroke="freeze" /> </line> <line x1="0" y1="30" x2="400" y2="30" style="stroke:black; stroke-width:1px;"> <animate id="a13" attributeName="stroke" from="black" to="red" dur="3s" begin="6s;al3.end+3s" stroke="freeze" /> </line> <line x1="0" y1="40" x2="400" y2="40" style="stroke:black; stroke-width:1px;"> <animate id="a14" attributeName="stroke" from="black" to="red" dur="3s" begin="9s;al4.end+3s" stroke="freeze" /> </line> </svg> 

您可以使用window.setTimeout在一定的延遲后執行函數來代替睡眠。 因此,您可以執行以下操作:

$('svg').find('line').each(function(index, element){
    window.setTimeout(function() {
        $(element).attr('style','stroke:red');
    }, index * 100);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM