Display an image after a time delay on html canvas

2.1k views Asked by At

I have an animation that when finished produces a still image. I want this image to be displayed for around 5 seconds before changing to another still image. I have tried various implementations of setTimeout to fix this but it hasnt worked for me.

Any help would be appreciated.

Heres my code:

(function drawFrame() {
  window.requestAnimationFrame(drawFrame, canvas);
  <!--ctx.clearRect(0, 0, cw, ch); -->
  image3 = new Image();
  image3.src = "broken1.png";
  ctx.drawImage(image3, 0, 0);
  setTimeout(function() {
    image4 = new Image();
    image4.src = "broken.png";
    ctx.drawImage(image4, 0, 0);
  }, 5000);
}())
1

There are 1 answers

0
AWolf On BEST ANSWER

Felix Kling is right, you should wrap your drawing in an onload callback. Please have a look at the following code below. jsFiddle to it is here.

(I've removed the requestAnimationFrame to make the code simpler, but I think that's not the problem here.)

$(function () {
    function drawFrame() {
        //window.requestAnimationFrame(drawFrame, canvas);
        var c = document.getElementById("container");
        var ctx = c.getContext("2d");
        //ctx.clearRect(0, 0, cw, ch);
        image3 = new Image();
        image3.onload = function() {
            ctx.drawImage(this, 0, 0);
            //console.log("loaded");
        };
        image3.src = "http://placehold.it/300x300";
        
        setTimeout(function () {
            image4 = new Image();
            
            image4.onload = function() {
                ctx.drawImage(this, 0, 0);
            };
            image4.src = "https://placekitten.com/g/300/300";
        }, 5000);
    }
    
    drawFrame();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="container"></canvas>