如何在javascript中为每个频谱栏添加类?

Posted

技术标签:

【中文标题】如何在javascript中为每个频谱栏添加类?【英文标题】:How to add class to each spectrum bar in javascript? 【发布时间】:2015-09-09 19:16:49 【问题描述】:

我想使用 javascript 可视化频谱条..所以我使用 web-audio API 并设法获得输出...但问题是如果我通过 css 更改条形颜色,所有条形都具有相同的颜色,但如果我随机化颜色通过javascript它可以工作,但不是我想要的那样工作。条的颜色不断变化,我希望它们是静态的。所以我想做的是为每个栏添加一个类或使颜色静态。 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

【问题讨论】:

【参考方案1】:

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

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 **/
    );
;

【讨论】:

以上是关于如何在javascript中为每个频谱栏添加类?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 iphone 中为导航栏添加自定义颜色?

如何在 Swift 中为导航栏添加阴影并隐藏边框?

如何在颤动中为标签栏下划线添加渐变?

如何在 android studio 中为初学者添加操作栏?

如何在导航栏中为非 rootviewcontroller 的 tableviewcontroller 添加编辑按钮

如何在 sass mixin 中为每个属性添加值? [复制]