简体   繁体   中英

How to add color to grayscale images with css / html or javascript?

I have a CP437 tileset:

在此处输入图片说明

which I want to use as a CSS sprite on a webpage Currently, I have a very simple markup and css:

.tile {
    display: inline-block;
    width: 16px;
    height: 16px;
}

.cp437-0 {
    background: url('tileset/tileset.png') 0 0;
}

.cp437-1 {
    background: url('tileset/tileset.png') 16px 0;
}

// ...

<span class="tile, cp437-0">&nbsp;</span>

This works very well, but I'd also like to add color to these grayscale sprites. How can I do this with using HTML/CSS or Javascript?

Is it possible to set background color for the resulting image?

Clarification:

I'd like to be able to draw things like these to the browser window using the sprite:

在此处输入图片说明 在此处输入图片说明

There's no pure CSS way to do this -- you'll need at least some SVG magic. For example, you can define a filter. It's, however, tricky to nail the color as it requires some not-so-trivial knowledge of maths, matrices and how computers work with colors.

Here's an example with golden images.

 .defs-only { position: fixed; left: -9999px; top: -9999px; z-index: -1; width: 1px; height: 1px; } img { filter: url(#monochrome); } 
 <svg class="defs-only"> <filter id="monochrome" color-interpolation-filters="sRGB" x="0" y="0" height="100%" width="100%"> <feColorMatrix type="matrix" values="1.00 0 0 0 0 0.80 0 0 0 0 0.65 0 0 0 0 0 0 0 1 0" /> </filter> </svg> <img src="https://i.stack.imgur.com/nQET4.png"> 

Check out, for example, this article for more info .

You could also use blend-modes but since your image is transparent, it will unfortunately apply the background-color to the... background, as well. If you can get the same image with the black background, it would work. A full list of blend modes if available at MDN, so you can play with different values.

 .sprite { width: 256px; height: 256px; background-image: url(https://i.stack.imgur.com/nQET4.png); background-color: #ab1248; background-blend-mode: hard-light; } 
 <div class="sprite"> 

If you work with transparent png, you can combine mask and mix-blend-mode

 .bubble{ display: inline-block; float: left; -webkit-mask: url(https://i.stack.imgur.com/og0JD.png); mix-blend-mode: normal; width:20px; height:20px; } #color1{ background-color:blue; } #color2{ background-color:red; } #color3{ background-color:green; } #color4{ background-color:yellow; } #color5{ background-color:pink; } 
 <div id="color1" class="bubble"></div> <div id="color2" class="bubble"></div> <div id="color3" class="bubble"></div> <div id="color4" class="bubble"></div> <div id="color5" class="bubble"></div> 

在此处输入图片说明

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