繁体   English   中英

获取半透明黑色div的结果背景色?

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

我有一个div元素,该元素具有黑色背景色集,并且具有很小的不透明度,可以与各种站点背景(白色,灰色,绿色等)混合。 有什么方法可以获取该元素的计算出的颜色吗? 我指的是用户可以看到的颜色(因此,不透明度+元素背景颜色+站点背景颜色的组合)。

当然,这必须由JavaScript完成,但我找不到执行此操作的方法或插件。 我知道JS中的backgroundColor ,但是那只会返回background-color CSS值: black

这是一个示例: http : //jsfiddle.net/N6EB8/

非常感谢你!

PS:我希望我足够清楚。 如果没有,请告诉我。

您可以创建一个隐藏的canvas元素,其宽度为100px,高度为1px,并且具有从前景色(在这种情况下为黑色)到背景色(在这种情况下为白色)的线性渐变。

然后,您可以使用ctx.getImageData()获取渐变上给定点的颜色。 除了乘以100外,您使用的x坐标将与div的不透明度相同。

getImageData()返回的数据可以直接在“ rgba”格式的背景颜色值中使用。

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

然后的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;

运作中的jsFiddle: http : //jsfiddle.net/zbC9u/6/

编辑:我更新了小提琴,使其更符合您的要求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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