HTML5 Canvas Make Black Transparent

喜欢而已 提交于 2019-12-04 13:58:04
ericjbasti

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.

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"/>

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!