Question

I have a linear gradient that is used as percentage bar with a small ellipse that moves along the bar to show the current completion percentage. The completion percentage is updated via an AngularJS binding that calls a function.

I need to change the color of the ellipse depending on the color of the gradient bar in the current position. Let'say the percentage is 80%, I need to get the color of the gradient at the 80% position.

Is that possible?

<svg height="20px" width="100%">
<defs>
    <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
        <stop offset="0%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
        <stop offset="50%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
        <stop offset="100%" style="stop-color:rgb(79,189,0);stop-opacity:1" />
    </linearGradient>
</defs>
<rect width="100%" height="3px" y="50%" fill="url(#gradient)" style="stroke-width:0" />
<rect width="30px" height="20px" x="{{calculateProfilePercentage()}}%" rx="8" ry="8" fill="rgb(249,166,31)" style="stroke-width:0" />
</svg>
Was it helpful?

Solution

AFAIK you cannot read a value off from a gradient as the gradient object do not expose methods to do so.

You can however create an off-screen canvas, draw a gradient and read the pixel value from there.

For example, lets create an object GradientReader. This allows us to instantiate it and embed methods and so forth:

function GradientReader(colorStops) {

    const canvas = document.createElement('canvas');   // create canvas element
    const ctx = canvas.getContext('2d');               // get context
    const gr = ctx.createLinearGradient(0, 0, 101, 0); // create a gradient
    
    canvas.width = 101;                                // 101 pixels incl.
    canvas.height = 1;                                 // as the gradient

    for (const { stop, color } of colorStops) {               // add color stops
        gr.addColorStop(stop, color);
    }
    
    ctx.fillStyle = gr;                                // set as fill style
    ctx.fillRect(0, 0, 101, 1);                        // draw a single line
    
    // method to get color of gradient at % position [0, 100]
    return {
        getColor: (pst) => ctx.getImageData(pst|0, 0, 1, 1).data
    };
}

Now we can setup the object with the color stops.

const gr = new GradientReader([{stop: 0.0, color: '#f00'},
                               {stop: 0.5, color: '#ff0'},
                               {stop: 1.0, color: 'rgb(79,189,0)'}]);

We now have an object which mimics the gradient and all we need to do now is to call its method getColor() with a percentage value:

const col = gr.getColor(pst);
el.style.backgroundColor = `rgb(${col[0]}, ${col[1]}, ${col[2]})`;

FIDDLE

Modify to your liking/needs.

Hope this helps!

OTHER TIPS

Here's my answer using the answer above in Angular 8 and some ES6 techniques.The new percentage is coming in through an observerable.

The HTML-file contains an SVG with two attributes linked to the class. Something like this:

<svg>
 <circle [attr.stroke]='strokeColor' [attr.fill]='fillColor'>
</svg>

app's Typescript file:

import {Component, Input, OnInit} from '@angular/core';
import {Observable} from 'rxjs';

@Component({
  selector: 'app-real-time-indicator',
  templateUrl: './real-time-indicator.component.html',
  styleUrls: ['./real-time-indicator.component.css']
})
export class RealTimeIndicatorComponent implements OnInit {

  @Input() percentagePassed$: Observable<number>;
  @Input() minutesRemaining$: Observable<number>;

  public currentPercentage: number;
  public minutesRemaining: number;
  private canvas2dContext: any;
  private canvas: any;

  public fillColor: string;
  public strokeColor: string;

  constructor() {

  }

  ngOnInit(): void {
    this.percentagePassed$.subscribe((newValue) => {
      this.currentPercentage = 100 - newValue;
      let [r, g, b]   = this.getColor( newValue);
      this.fillColor = `rgb(${r},${g},${b})`;

      [r, g, b]   = this.getColor( 100 - newValue);
      this.strokeColor = `rgb(${r},${g},${b})`;
    });
    this.canvas = document.createElement('canvas');     // create canvas element
    this.canvas2dContext = this.canvas.getContext('2d');                 // get context
    const gr = this.canvas2dContext.createLinearGradient(0, 0, 101, 0);   // create a gradient

    this.canvas.width = 101;                                // 101 pixels incl.
    this.canvas.height = 1;                                 // as the gradient

    const colorStops = [
      {stop: 0.0, color: 'lightgreen'},
      {stop: 0.9, color: 'orange'},
      {stop: 1.0, color: 'red'},
    ];

    for (const cs of colorStops)                       // add color stops
    {
      gr.addColorStop(cs.stop, cs.color);
    }

    this.canvas2dContext.fillStyle = gr;                                // set as fill style
    this.canvas2dContext.fillRect(0, 0, 101, 1);                        // draw a single line

  }

  // method to get color of gradient at % position [0, 100]
  getColor(percentage: number) {
    return this.canvas2dContext.getImageData(percentage , 0, 1, 1).data;
  }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top