How to edit pixels and remove white background in a canvas image in HTML and JavaScript?

Sometimes, we want to edit pixels and remove white background in a canvas image in HTML and JavaScript.

In this article, we’ll look at how to edit pixels and remove white background in a canvas image in HTML and JavaScript.

How to edit pixels and remove white background in a canvas image in HTML and JavaScript?

To edit pixels and remove white background in a canvas image in HTML and JavaScript, we can loop through the canvas pixels and change their color.

For instance, we write:

<canvas width='200' height='300'></canvas>

to add a canvas.

Then we write

const canvas = document.querySelector("canvas")
const ctx = canvas.getContext("2d")
const image = new Image()
image.onload = () => {
  canvas.height = canvas.width = 135;
  ctx.drawImage(image, 0, 0);
  const imgd = ctx.getImageData(0, 0, 135, 135),
    pix = imgd.data,
    newColor = {
      r: 0,
      g: 0,
      b: 0,
      a: 0
    };

  for (let i = 0, n = pix.length; i < n; i += 4) {
    const r = pix[i],
      g = pix[i + 1],
      b = pix[i + 2];
    if (r === 255 && g === 255 && b == 255) {
      pix[i] = newColor.r;
      pix[i + 1] = newColor.g;
      pix[i + 2] = newColor.b;
      pix[i + 3] = newColor.a;
    }
  }
  ctx.putImageData(imgd, 0, 0);
}
image.src = 'https://picsum.photos/200/300'

to select the canvas with querySelector.

In the image.onload method, we loop through the canvas image data we got from getImageData.

And we check for white with r === 255 && g === 255 && b == 255.

If that’s true, then we set the pixels to new rgba values.

We then call putImageData to draw the new pixels.

image.onload runs after image.src is set.

Conclusion

To edit pixels and remove white background in a canvas image in HTML and JavaScript, we can loop through the canvas pixels and change their color.