JSFiddle - React, Tailwind, and code Playground
by swesh
JavaScript
// source file to load
var file = "http://a.dilcdn.com/bl/wp-content/uploads/sites/8/2012/09/02-11.jpg";
// color to make transparent. Magenta here...
var transparentColor = {
r : 255,
g : 0,
b : 255
};
var img = new Image();
img.src = file;
img.onload = function(){
// create a source canvas. This is our pixel source
var srcCanvas = document.createElement("canvas");
srcCanvas.width = img.width;
srcCanvas.height = img.height;
// create a destination canvas. Here the altered image will be placed
var dstCanvas = document.createElement("canvas");
dstCanvas.width = img.width;
dstCanvas.height = img.height;
// append the canvas elements to the container
document.getElementById('container').appendChild(srcCanvas);
document.getElementById('container').appendChild(dstCanvas);
// get context to work with
var srcContext = srcCanvas.getContext("2d");
var dstContext = dstCanvas.getContext("2d");
// draw the loaded image on the source canvas
srcContext.drawImage(img, 0, 0);
// read pixels from source
var pixels = srcContext.getImageData(0, 0, img.width, img.height);
// iterate through pixel data (1 pixels consists of 4 ints in the array)
for(var i = 0, len = pixels.data.length; i < len; i += 4){
var r = pixels.data[i];
var g = pixels.data[i+1];
var b = pixels.data[i+2];
// if the pixel matches our transparent color, set alpha to 0
if(r == transparentColor.r && g == transparentColor.g && b == transparentColor.b){
pixels.data[i+3] = 0;
}
}
// write pixel data to destination context
dstContext.putImageData(pixels,0,0);
}