how to edit pixels and remove white background in a canvas image in html5 and javascript

后端 未结 3 1134
时光取名叫无心
时光取名叫无心 2020-12-04 23:09

If I load an image, how can I loop through all its pixels and turn the white ones (or which ever color I specify) to be turned transparent?

I have an idea on how to

3条回答
  •  不知归路
    2020-12-04 23:17

    Its pretty simple to do using getImageData and putImageData just note you can take a pretty significant hit on performance the larger the image gets. You just need to determine if the current pixel is white, then change its alpha to 0.

    Live Demo

    var canvas = document.getElementById("canvas"),
        ctx = canvas.getContext("2d"),
        image = document.getElementById("testImage");
    
    canvas.height = canvas.width = 135;
    ctx.drawImage(image,0,0);
    
    var imgd = ctx.getImageData(0, 0, 135, 135),
        pix = imgd.data,
        newColor = {r:0,g:0,b:0, a:0};
    
    for (var i = 0, n = pix.length; i 

    It was also asked if you could make the values sort of fuzzy to check. Its really easy, just check if its in a certain range. The following will turn off white to pure white transparent.

     // If its white or close then change it
        if(r >=230 && g >= 230 && b >= 230){ 
            // Change the white to whatever.
            pix[i] = newColor.r;
            pix[i+1] = newColor.g;
            pix[i+2] = newColor.b;
            pix[i+3] = newColor.a;
        }
    

    More resources

    • Pixel manipulation with canvas
    • Further info on pixel manipulation with canvas

提交回复
热议问题