from green to red color depend on percentage

前端 未结 14 2031
北恋
北恋 2020-11-30 20:00

I have a poll system and I want answers for this poll to be colored. For example: If it\'s 10% it would be red, if 40% it would be yellow and if 80% it would be green, so I

14条回答
  •  失恋的感觉
    2020-11-30 20:45

    You can do this in a few lines of code (not including comments) without the need for any color maps.

    function hsl_col_perc(percent, start, end) {
      var a = percent / 100,
          b = (end - start) * a,
          c = b + start;
    
      // Return a CSS HSL string
      return 'hsl('+c+', 100%, 50%)';
    }
    //Change the start and end values to reflect the hue map
    //Refernece : http://www.ncl.ucar.edu/Applications/Images/colormap_6_3_lg.png
    
    /*
    Quick ref:
        0 – red
        60 – yellow
        120 – green
        180 – turquoise
        240 – blue
        300 – pink
        360 – red
    */      
    

    Example: https://jsfiddle.net/x363g1yc/634/

    No need for color maps (Unless it is a non-linear color change, which was not asked)

    Warning: This is not compatible with IE8 or below. (Thanks Bernhard Fürst)

    // Just used as a shortcut for below, completely optional
    const red = 0,
      yellow = 60,
      green = 120,
      turquoise = 180,
      blue = 240,
      pink = 300;
    
    function hsl_col_perc(percent, start, end) {
      var a = percent / 100,
        b = (end - start) * a,
        c = b + start;
    
      // Return a CSS HSL string
      return 'hsl(' + c + ', 100%, 50%)';
    }
    
    // Simple little animation
    var percent = 0,
      progressDiv = document.getElementById('progress'),
      textDiv = document.getElementById('progress-text'),
      progressContainerDiv = document.getElementById('progress-container')
    
    function step(timestamp) {
      percent = (percent < 100) ? percent + 0.5 : 0;
    
      // Play with me!
      let colour = hsl_col_perc(percent, red, green); //Red -> Green
      progressDiv.style.backgroundColor = colour;
      progressContainerDiv.style.borderColor = colour;
      progressDiv.style.width = percent + '%';
      textDiv.innerHTML = Math.floor(percent);
      window.requestAnimationFrame(step);
    }
    
    window.requestAnimationFrame(step);
    #progress {
      width: 0%;
      white-space: nowrap;
      text-wrap: none;
      height: 50px;
    }
    
    #progress-container {
      border: solid 2px black;
      width: 200px;
    }

提交回复
热议问题