3

Given a div that has an image in its background, if this image is transparent (this is an important detail), how can I change its color? Is it possible?

HTML

<body>
    <div>
        <hr/>
        <div id ='imagediv' class="ornament"></div>
    </div>
</body>

CSS

body {
margin-top: 100px; 
background: url('http://hostmypicture.com/images/fundokairo.png') repeat;
}

hr {
    height: 30px;
    color: #578daf;
    background: url('http://hostmypicture.com/images/barrapreta.png') repeat-x 0 50%;
    border: 0;
    padding: 0; 
    margin: 9px 0 0 0;
}

.ornament {
    width: 169px;
    height: 169px;
    background: url('http://s23.postimg.org/6prq112g7/mascara_Fundo_Branco_Kairos.png') 0 50%;
    margin: -104px auto 0 auto;
} 

ornament is the class of the div.

JavaScript

var divImage = document.getElementById('imagediv');
var divStyle = divImage.currentStyle || window.getComputedStyle(divImage, false);
var divBackImage = divStyle.backgroundImage;

How can the image be filled?


I tried without success to fill the image using fillStyle and fill() of JavaScript. But it seems that using canvas is a possibility.


Fiddle: http://jsfiddle.net/9EFdF/21/

Note: I want the effect of a progress bar, so the color needs to come from underside.

4

2 回答 2

2

您可以像这样简单地为元素设置新样式 - 注意:它将改变图像的透明部分,因此在这种情况下,如果您希望内部部分更改颜色更改透明度以使该部分透明:

imagediv.style.backgroundColor = '#000'; //new color

您可以选择首先使用getElementById,但是,可以直接引用具有 ID 的元素,但例如为了:

var el = document.getElementById('imagediv');
el.style.backgroundColor = '#000'; //new color

UPDATED FIDDLE

如果您想保持图像原样并填充其内部,则唯一的其他选择是使用画布及其合成模式。

于 2013-07-18T14:29:12.247 回答
1

如果 div 与背景图像大小相同,您可以background-color为 div 添加样式,颜色将通过透明图像显示。

于 2013-07-18T14:26:54.557 回答