HTML5 Canvas Make Black Transparent

2019-04-11 18:43发布

问题:

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

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

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

回答1:

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.



回答2:

You can accomplish that using blend modes.

Change the context globalCompositeOperation to screen, and you can get that result. Here's an example:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");


var image = new Image();
image.src = "https://images.blogthings.com/thecolorfulpatterntest/pattern-4.png";

image.onload = function() {
  context.drawImage(image, 0, 0, canvas.width, canvas.height);

  var blackImage = new Image();
  blackImage.src="http://www.printmag.com/wp-content/uploads/Sillitoe-black-white.gif";
  blackImage.onload = function(){
    context.globalCompositeOperation = "screen";
    context.drawImage(blackImage, 0, 0, canvas.width, canvas.height);
  }

};
<canvas id="canvas" width="300" height="250"></canvas>

<hr/>
<h1>Images used:</h1>

<img src="https://images.blogthings.com/thecolorfulpatterntest/pattern-4.png"/>

<img src="http://www.printmag.com/wp-content/uploads/Sillitoe-black-white.gif"/>



回答3:

How about saving the picture as an .svg file...from there you can change all colors and other settings