JSFiddle - React, Tailwind, and code Playground

by Gabriele Petrioli

HTML

before: <img src="http://fiddle.jshell.net/img/logo-white.png"/>
<hr />
after : <img id="image" src="http://fiddle.jshell.net/img/logo-white.png"/>
<hr />
<button>clear white</button>

CSS

body{background-color:red;}

JavaScript

$('button').click(function(){
    var after = $('#image')[0];
    after.src = white2transparent(after);
})

function white2transparent(img)
{
    var c = document.createElement('canvas');
    
    var w = img.width, h = img.height;
    
    c.width = w;
    c.height = h;
        
    var ctx = c.getContext('2d');
    
    ctx.width = w;
    ctx.height = h;
    ctx.drawImage(img, 0, 0, w, h);
    var imageData = ctx.getImageData(0,0, w, h);
    var pixel = imageData.data;
    
    var r=0, g=1, b=2,a=3;
    for (var p = 0; p<pixel.length; p+=4)
    {
      if (
          pixel[p+r] == 255 &&
          pixel[p+g] == 255 &&
          pixel[p+b] == 255) // if white then change alpha to 0
      {pixel[p+a] = 0;}
    }
    
    ctx.putImageData(imageData,0,0);
    
    return c.toDataURL('image/png');
}