from green to red color depend on percentage

前端 未结 14 2049
北恋
北恋 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:47

    Mattisdada's code was really helpful for me while I was making a chart to display statistics of some quiz results. I modified it a bit to allow "clipping" of the percentage (not sure what the right term is) and also to work both ways along the colour wheel, e.g. both from green(120) to red(0) and vice versa.

    function pickColourByScale(percent, clip, saturation, start, end)
    {
        var a = (percent <= clip) ? 0 : (((percent - clip) / (100 - clip))),
            b = Math.abs(end - start) * a,
            c = (end > start) ? (start + b) : (start - b);
        return 'hsl(' + c + ','+ saturation +'%,50%)';
    }
    

    Basically, by setting a percentage value to clip the scaling at, everything below that value will be coloured as your start colour. It also recalculates the scaling according to 100% - clip.

    Let's go through an example scenario where I enter the following values:

    • percent: 75
    • clip: 50
    • saturation: 100 (unimportant, I use this for highlighting a Chart.js chart)
    • start: 0 (red)
    • end: 120 (green)

      1. I check if percent is less than clip, and I return 0% if it is. Otherwise, I recalculate the percentage - 75% is halfway between 50% and 100%, so I get 50%. This gives me 0.5.
      2. I get the difference between start and end. You need to use Math.abs() in case your start hue value is more than your end hue value. Then I multiply the difference by the result obtained in step 1 to see how much I need to offset the start hue value.
      3. If the start value is more than the end value, then you need to move along the colour wheel in the opposite direction. Add to or subtract from the start value accordingly.

    I end up with yellow, which is halfway between red and green. If I hadn't done the recalculation in step 1, I'd have ended up with a more greenish colour, which could be misleading.

提交回复
热议问题