Viswanatham Santosh
Viswanatham Santosh

Reputation: 11

.gif image as canvas background

I want to set a .gif image as a background image of a canvas so that i would get an animated view of the background.but i was getting only a static image displayed on it.

Here is my HTML code of my windows 8 app.

<body>
  <canvas id="canvas"></canvas>
  <img id="scream" src="images/gangam.gif" alt="The Scream" width="220" height="277">
</body>
<script>
  var canvas = document.getElementById("canvas"),
      ctx = canvas.getContext("2d"); // Create canvas context                                                                          

  function paintCanvas() {
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, W, H);
    var img = document.getElementById("scream");
    ctx.drawImage(img, W/2, H/2);
  }
</script>

Upvotes: 1

Views: 3556

Answers (2)

Omar Al-Ithawi
Omar Al-Ithawi

Reputation: 5170

Why not letting the canvas be transparent, and placing (CSS positioning) the canvas above it? Isn't this better than having to do low-level imaging stuff?

Otherwise canvas shows only one static image at a time, of course your JavaScript could animate it but that doesn't it's staticness.

Check this fiddle: http://jsfiddle.net/pK7Xx/2/

CSS

#canvas, #scream {
    width: 500px;
    height: 212px;
    position: relative;
    display: block;
}

#canvas {
    margin-top: -212px;
}

HTML

<img id="scream" src="http://24.media.tumblr.com/tumblr_ma1wafniaA1rbonrno1_500.gif" alt="The Scream">
 <canvas id="canvas"></canvas>

Draw Using a Transparent Canvas var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"); // Create canvas context

function something() {
context.font = "bold 25px sans-serif";
context.fillText("Hello!", 100, 43);
}

something();

Upvotes: 2

Radosław Miernik
Radosław Miernik

Reputation: 4094

No, there's no way to show a .gif in <canvas>. You might use sprites and setInterval() to imitate animation.

Upvotes: 1

Related Questions