naikus / svg-gauge

Minimalistic, animated SVG gauge. Zero dependencies
MIT License
319 stars 74 forks source link

Changing color while value increase #5

Closed ghost closed 7 years ago

ghost commented 7 years ago

Hello,

Is it possible to implement changing color when value displayed on the gauge gradually increase ? For example, begin from green and finish to red.

Thank you a lot for your consideration.

naikus commented 7 years ago

@lutchit I'll look into this. Thanks!

wmelton commented 7 years ago
var percentColors = [
    { pct: 0.0, color: { r: 0x00, g: 0xff, b: 0 } },
    { pct: 0.5, color: { r: 0xff, g: 0xff, b: 0 } },
    { pct: 1.0, color: { r: 0xff, g: 0x00, b: 0 } } ];

var getColorForPercentage = function(pct) {
    for (var i = 1; i < percentColors.length - 1; i++) {
        if (pct < percentColors[i].pct) {
            break;
        }
    }
    var lower = percentColors[i - 1];
    var upper = percentColors[i];
    var range = upper.pct - lower.pct;
    var rangePct = (pct - lower.pct) / range;
    var pctLower = 1 - rangePct;
    var pctUpper = rangePct;
    var color = {
        r: Math.floor(lower.color.r * pctLower + upper.color.r * pctUpper),
        g: Math.floor(lower.color.g * pctLower + upper.color.g * pctUpper),
        b: Math.floor(lower.color.b * pctLower + upper.color.b * pctUpper)
    };
    return 'rgb(' + [color.r, color.g, color.b].join(',') + ')';
    // or output as hex if preferred
} 

$('.gauge-container > .gauge > .value').css('stroke', getColorForPercentage(value2 / 100));

Modify CSS rule:

.gauge-container > .gauge > .value {
  stroke: rgb(47, 227, 255);
  stroke-width: 20;
  fill: rgba(0,0,0,0);
   -webkit-transition: stroke 2s ease-out;
  -moz-transition: stroke 2s ease-out;
  -o-transition: stroke 2s ease-out;
  transition: stroke 2s ease-out;
}
wmelton commented 7 years ago

JS Fiddle:

https://jsfiddle.net/r6Lth6tq/19/

naikus commented 7 years ago

Hello @lutchit @wmelton I've created a new branches with support to change dial color based on values. Please see the branch: dial-color-chnage #7

naikus commented 7 years ago

Fixed in commit 22241a7