简体   繁体   中英

Get the resulted background color of a semi-transparent black div?

I have a div element that has a black background color set and a small opacity to blend in with various site backgrounds (white, gray, green etc). Is there any way I can get the computed color of that element? I am referring to that color that users can see (so the combination of the opacity + element background color + site background color).

Of course this has to be done by JavaScript but I can't find a way or a plugin that does this. I know about backgroundColor in JS but that would only return the background-color CSS value: black .

Here is an example: http://jsfiddle.net/N6EB8/

Thank you very much!

PS: I hope I was clear enough. If not, please let me know.

You could create a hidden canvas element with a width of 100px, a height of 1px, and a linear gradient from the foreground colour (black in this case) to the background colour (white in this case).

Then you could use ctx.getImageData() to get the colour at a given point on the gradient. The x coordinate you use would be the same as the opacity of the div, except multiplied by 100.

The data that getImageData() returns can be used directly in an 'rgba' formatted background-color value.

<div id="myDiv" style="opacity:0.3;"></div>

Then the javascript:

//get the div's opacity
var myDiv = document.getElementById('myDiv');
var divOpc = myDiv.style.opacity;
/*
  To get the opacity, you'll probably want to use 
  jquery's $(myDiv).css('opacity'), unless the opacity is in 
  the 'style' attribute.
  If you wanted to keep it vanilla JS, you could use getComputedStyle().
*/


//create hidden canvas
var cvs = document.createElement('canvas');
cvs.style.display = 'none';
cvs.width = 100;
cvs.height = 1;
document.body.appendChild(cvs);

//give canvas a gradient
var ctx = cvs.getContext('2d');
var grd = ctx.createLinearGradient(0,0,100,0);
grd.addColorStop(0,'black'); //foreground colour
grd.addColorStop(1,'white'); //background colour
/*
  If you wanted to make this dynamic, you would get the 
  current background colour of the foreground/background element, 
  instead of hard-coding a colour.
*/
ctx.fillStyle = grd;
ctx.fillRect(0,0,100,1);

//The Magic!
var imgData = ctx.getImageData((100 - divOpc*100),0,1,1);
var formattedBG = 'rgba('+imgData.data[0]+','+imgData.data[1]+','+imgData.data[2]+',1)';
//Do something with that discovered bg colour.
//As an example: Give the background to a different div
var bgRecipient = document.getElementById('bgRecipient');
bgRecipient.style.backgroundColor = formattedBG;

Working jsFiddle: http://jsfiddle.net/zbC9u/6/

Edit: I updated the fiddle to match yours a bit more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM