如何将class添加到javascript中的每个频谱条?

How to add class to each spectrum bar in javascript?

我想使用 javascript 可视化频谱条..所以我使用网络音频 API 并设法获得输出...但问题是如果我通过 css 所有条形都有相同的颜色,但如果我通过 javascript 随机化颜色,它会起作用,但不是我想要的那样。条形的颜色不断变化,我希望它们是静态的。所以我想做的是在每个栏中添加一个 class 或使颜色保持不变。 HTml

    `<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">    <title>Trackest</title>
    <link rel="stylesheet" href="./css/style.css" />
  </head>

  <body>
  <header>
      <nav>
    <ul>
      <li class="left logo"><a href="" class="">Trackest</a></li>
      <li class="sub"><a href="" class="btn right">Welcome</a></li>
      <li class="sub"><a href="" class="btn right">Welcome</a></li>
    </ul>
  </nav>
  </header>

  <div class="hero-img">
    <div id="img"></div>
    <div id="player">
     <audio id="vir" class="hideIfNoApi" controls="controls" src="Nights.mp3" > </audio>
      <div id="vis" class="hideIfNoApi"> </div>
      </div>
  </div>

    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <script src="app.js"></script>
  </body>
</html>`

CSS

   #player audio {
    width: 100%;
}
#player{
top: 50%;}
#player .showNoApi {
    display: none;
}

.hero-img #vis {
   position:absolute;
     width:100%;
     height:500px;
     z-index:15;
 bottom: 0;    }

#player #vis > div {

    width: 2.5%;
    display: inline-block;
    position: absolute;
    bottom: 0px;
}

Javascript

$(function () {
    var context;
    if (typeof AudioContext !== "undefined") {
        context = new AudioContext();
    } else if (typeof webkitAudioContext !== "undefined") {
        context = new webkitAudioContext();
    } else {

        $(".showNoApi").show();
        return;
    }

    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame']
                                    || window[vendors[x] + 'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function (callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function () { callback(currTime + timeToCall); },
                timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function (id) {
            clearTimeout(id);
        };

    var analyser = context.createAnalyser();
    analyser.fftSize = 64;
    var frequencyData = new Uint8Array(analyser.frequencyBinCount);


    var vis = $("#vis");
  var barSpacingPercent = 100 / analyser.frequencyBinCount;
    for (var i = 0; i < analyser.frequencyBinCount; i++) {
      $("<div/>").css("left", i * barSpacingPercent + "%")
      .appendTo(vis);
    }
    var bars = $("#vis > div");
    function randColor() {
    var color = (function lol(m, s, c) {
                    return s[m.floor(m.random() * s.length)] +
                        (c && lol(m, s, c - 1));
                })(Math, 'fe2', 4);
    return color;
}

    function update() {
        requestAnimationFrame(update);

        analyser.getByteFrequencyData(frequencyData);
        bars.each(function (index, bar) {
            bar.style.height = frequencyData[index] + 'px';
            bar.style.background = '#' + randColor();
            bar.classList.add('YourClass');
        });
    };

  $("#vir").bind('canplay', function() {
    var source = context.createMediaElementSource(this);
    source.connect(analyser);
    analyser.connect(context.destination);
  });

    update();
});

这是演示:experimentos.ml/galaxy/ 图片:image

在开始更新之前设置背景颜色或class。我只包含了相关更改:

var bars = $("#vis > div");

bars.each(function (index, bar) { // this will run only once. Decide if you want to set the background or the class
    bar.style.background = '#' + randColor();
    bar.classList.add('barColor' + index); // if you want to use classes, create the maximum expected amount of classes with names like barColor1, barColor2... and then you can use index to set the right class
});

function randColor() {
    var color = (function lol(m, s, c) {
        return s[m.floor(m.random() * s.length)] +
        (c && lol(m, s, c - 1));
    })(Math, 'fe2', 4);
    return color;
}

function update() {
    requestAnimationFrame(update);

    analyser.getByteFrequencyData(frequencyData);
    bars.each(function (index, bar) {
        bar.style.height = frequencyData[index] + 'px';
        /**  bar.style.background = '#' + randColor(); - remove this so it won't change all the time **/
        /**  bar.classList.add('YourClass'); - remove this so it won't be set all the time **/
    });
};