Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Canvas Make Black Transparent

I have a large amount of images with a black background, here is one for example:

enter image description here

Is it possible through Javascript to have to ignore the black (#000000) and have it draw on canvas? to appear like this?

enter image description here

Basically trying to take the black pixels and make it an alpha channel.

like image 259
Sosa Avatar asked Feb 26 '16 03:02

Sosa


1 Answers

So you'll need to run through all the pixels and change the alpha value of all the black pixels.

https://jsfiddle.net/0kuph15a/2/

This code creates a buffer (empty canvas) to draw the original image to. Once thats done, it takes all the pixels of this buffer canvas and then iterates over all the pixels and checks their values. I add up the Red, Blue, and Green values to see if they are less then 10 (just incase some pixels aren't pure black 0), but would visually appear black to the human eye. If it is less then 10 it simply turns the alpha value of that pixel to 0.

var canvas = document.getElementById('main');

var ctx = document.getElementById('main').getContext('2d');
var tile = new Image();
tile.src = document.getElementById('image').src;
tile.onload = function() {
    draw(tile);
}

function draw(img) {
    var buffer = document.createElement('canvas');
    var bufferctx = buffer.getContext('2d');
    bufferctx.drawImage(img, 0, 0);
    var imageData = bufferctx.getImageData(0,0,buffer.width,  buffer.height);
    var data = imageData.data;
    var removeBlack = function() {
        for (var i = 0; i < data.length; i += 4) {
            if(data[i]+ data[i + 1] + data[i + 2] < 10){ 
                data[i + 3] = 0; // alpha
            }
        } 
        ctx.putImageData(imageData, 0, 0); 
    }; 
 removeBlack(); 
} 

You can easily change this line if(data[i]+ data[i + 1] + data[i + 2] < 10){ to if(data[i]+ data[i+1] + data[i+2]==0){ if you know for a fact only #000 blacks are used.

like image 53
ericjbasti Avatar answered Oct 12 '22 20:10

ericjbasti