Transparent background image html5 canvas

I am embedding an image in my canvas using this:

ctx.drawImage (myImageObject, 0, 0);

it works fine, except that the image I am pasting has some parts of it as transparent and the canvas seems to ignore this and it just prints what should be transparent as white pixels.

Here is the image I'm pasting: http://i44.tinypic.com/25ymq.gif

I researched this abit problem and some people fixed it by doing ctx.getImageData (0, 0, width, height) .data and then iterating through that array replacing pixels manually for transparency. I also read that this is bad practice because its slow (and my sprite sheets can be 1000 x 1000 and so it must be very slow).

Is there something I can do to make the transparency appear in my gif? When I saved it in photoshop and when I look at the gif I see transparency, but as soon as I paste it into the canvas it stops being transparent.

edit : I just tried another gif and the transparency works, but in the one above it is not, maybe the problem with the above gif?

+3


source to share


1 answer


Works fine for me with this image and the following code in the latest Firefox and Chrome on Mac. (Except for the image itself, there are a few white, opaque pixels that you can see when you open them against a dark background, such as Firefox.)



<!DOCTYPE HTML> 
<html>
<head>
<script type="application/x-javascript">
var canvas, ctx;

function init() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");

  var size=500;
  ctx.fillStyle = 'yellow';
  ctx.beginPath();
  ctx.fillStyle = 'yellow';
  ctx.moveTo(0,0);
  ctx.lineTo(size,0);
  ctx.lineTo(size,size);
  ctx.lineTo(0,size);
  ctx.lineTo(0,0);
  ctx.stroke();
  ctx.fill();

  var img = document.getElementById("img");
  ctx.drawImage(img, 0, 0);
}
</script>


</head>


<body onload="init();">

  <canvas id="canvas" width="500" height="500"></canvas>

  <img id="img" src="test.gif" style="position:absolute; top:500px"></img>

</body>
</html>

      

+2


source







All Articles