Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
How can I convert a canvas to an image with transparency?

I am currently trying to take a weather radar image that has a black background, and make the background transparent. I am using canvas to do this. When I display the image, the background that should be transparent now looks like a red and black checkerboard pattern. See here:

weather radar with red-and-black checkerboard background

The code being used is here:

function removeBlack(img) {
  // Create canvas and draw image
  let tmpCanvas = document.createElement('canvas');
  tmpCanvas.width = img.width;
  tmpCanvas.height = img.height;
  let tmpCtx = tmpCanvas.getContext('2d');
  tmpCtx.drawImage(img, 0, 0, tmpCanvas.width, tmpCanvas.height);

  // Get image data and add opacity to black pixels
  let imgData = tmpCtx.getImageData(0, 0, tmpCanvas.width, tmpCanvas.height);
  let data = imgData.data;
  for (var i = 0; i < data.length; i += 4) {
    let r = data[i],
        g = data[i+1],
        b = data[i+2];
    
    if (r === 0 && g === 0 && b === 0) data[i + 4] = 255;
  }

  tmpCtx.putImageData(imgData, 0, 0);
  imgData = tmpCanvas.toDataURL("image/png");
  
  let image = document.createElement('img');
  image.src = imgData;
  img.remove();
  tmpCanvas.remove();
  return image;
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Should be data[i + 3] = 255 in your loop

data[i + 4] will go into the next 32-bit colour word and set the red byte to maximum

Ps: you'll also have to test if the alpha value should be 0 or 255 - 255 might be fully opaque rather than transparent

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!