Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get background colour from linear-gradient color value

Tags:

jquery

how could i get the color-code from a linear gradient value using jQuery.Suppose if I have a linear gradient value as

background:linear-gradient(to right, #fff 87%,rgba(238,237,233,0) 100%);

how could i extract the color code from this.I should be getting the final output as #fff in this case..I tried using

$('selector').css('background-color');

which does not help me get the color-code.Could someone help me figure this out.Thanks.. :)

like image 957
Outlooker Avatar asked Jun 21 '14 12:06

Outlooker


People also ask

Can I use linear gradient in background color?

Because <gradient> s belong to the <image> data type, they can only be used where <image> s can be used. For this reason, linear-gradient() won't work on background-color and other properties that use the <color> data type.

How do I create a gradient fill background?

Click the “Design” pane on the main menu bar across your screen. Click on the “format background” option. Switch to “gradient fill” Create your custom gradient of two, three, or more colors by adding in color stops.


1 Answers

One possible solution would be to create a canvas element using the 'selector' class|id to style it.

Then you could establish the RGBA of a pixel on that canvas.. VERY 'hacky' but its the only thing my little brain can think of!

Something like this (Not tested!):

Lets say your html looks something like this :

<style>
.background_element{
background:linear-gradient(to right, #fff 87%,rgba(238,237,233,0) 100%);
}
</style>

Then you want to check the background colour .. so we create a canvas object to clone the div at that time.

var canvas = document.createElement('canvas');
//apply width and heigh 1px
canvas.css('background-color', $('.background_element').style.backgroundColor);

Then we cant to get the colour of a pixel on this canvas..

var pixelData = this.canvas.getContext('2d').getImageData(1, 1, 1, 1).data;
console.log('R: ' + pixelData[0] + '<br>G: ' + pixelData[1] + '<br>B: ' + pixelData[2] + '<br>A: ' + pixelData[3]);

This would log the RGBA to the console.. Maybe..

- Note: I dont recommend this for production env of course, meerly a proof of concept!

Inspiration

Alternatively

You could be very fancy and really strip into the RGBA with HTMLelement.prototype.alpha! :)

Something like :

HTMLElement.prototype.alpha = function(a) {
        current_color = getComputedStyle(this).getPropertyValue("background-color");
        match = /rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*\d+[\.\d+]*)*\)/g.exec(current_color)
        a = a > 1 ? (a / 100) : a;
        console.log("rgba(" + [match[1],match[2],match[3],a].join(',') +")");
      }

Again very messy but there is a good chance this will be more percise !

like image 151
Pogrindis Avatar answered Oct 12 '22 23:10

Pogrindis