Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

197
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda