Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda