简体   繁体   中英

transparent image background html5 canvas

I'm inserting an image into my canvas with this:

ctx.drawImage(myImageObject, 0, 0);

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

Here is the image I am inserting: http://i44.tinypic.com/25ymq.gif

I researched this problem abit 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 practise because its slow (and my sprite sheets could be 1000 x 1000 and so this WOULD be very slow).

Is it possible to do something to make the transparency in my gif show up? When I saved it in photoshop and when I look at the gif itself I can see the transparency, but as soon as I stick it in a canvas it stops being transparent.

edit : I just tried another gif and the transparency works, but in the one above it does not, could there possibly be a problem with the above gif?

Works fine for me with that image and the following code in the latest Firefox and Chrome beta on Mac. (Except the image itself has a few white non-transparent pixels, which you can see by opening on a dark background eg in 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM