简体   繁体   English

如何使用JavaScript循环动态更改SVG对象的颜色?

[英]How to dynamically change the SVG object color using a JavaScript loop?

I constructed a network with about 1000 nodes in SVG format. 我构建了一个包含约1000个SVG格式节点的网络。 Now I want to change the color of all the nodes dynamically (with time). 现在,我想动态地(随时间)更改所有节点的颜色。 For starters I just want to make sure that the circles/nodes in my SVG figure change colors with time based on a random number generator. 首先,我只想确保SVG图形中的圆圈/节点基于随机数生成器随时间改变颜色。 Can I use a simple for loop in JavaScript to bring about N number of node color changing events? 我可以在JavaScript中使用简单的for循环来引发N个节点颜色更改事件吗?

This is the function I wrote hoping that it would change the color of a particular node/circle hundred times triggered by single mouse click 这是我编写的函数,希望它可以通过单击一次鼠标来改变特定节点/圆圈的颜色一百次

function ChangeRandomNodeColor(){
  var mycircle = document.getElementById("node_1150")   
  for (i = 0; i < 100 ; i++) {
    var r = Math.random()
    if (r < 0.33) {
      mycircle.style.fill = "yellow" ;
    } 
    else if (r < 0.66) {
      mycircle.style.fill = "cyan" ;
    } 
    else {
      mycircle.style.fill = "black" ;
    }
  }
}

Unfortunately all it does is to change the color only once per every mouse click, it's as though the for loop is completely useless! 不幸的是,它所做的只是每次单击鼠标一次更改颜色,就好像for循环完全没用!

Let us consdider following rect as one node . 让我们考虑将rect作为一个节点。 Use window.setInterval function for timer and use Math.Random fucntion to generate a random number and use according your requirement. 将window.setInterval函数用于计时器,并使用Math.Random功能生成随机数,然后根据需要使用。

  <svg>
      <rect width="100px" height="100px" fill="yellow" id="one">
      </rect>
  <svg>

document.getElementById("one").style.fill = "red";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM