make2514
make2514

Reputation: 43

Animation is not very smooth when making a image slide effect using HTML canvas

I want to make an image slide effect using HTML5 canvas. I am able to "slide" the image by translating the canvas and redrawing the image. However, during the slide process, the canvas cleared and the left of the image redrawn causes some flickering along the left side if the image. Here is a demo link: http://codepen.io/make2514/pen/rLQwbz. Below is my script for canvas:

var img = new Image();
var imgLoaded = false;
img.src = "http://in5d.com/wp-content/uploads/2014/11/SHMNTYMETM.jpg"
img.onload = function(){
    imgLoaded = true;
};

var canvas = document.querySelector('canvas');

function play() {

    push(canvas, img, function () {
        console.log('done');
    });
}

function push (canvas, canvasIn) {
    var ctx = canvas.getContext('2d'); 

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    if (imgLoaded) {
      ctx.translate(5, 0);
    }
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

    window.requestAnimationFrame(function () {
        push(canvas, img);
    });
}

I try to reduce the x-axis canvas translation to smaller value but the flickering is still there.

I would really appreciate any suggestion!

Upvotes: 1

Views: 316

Answers (1)

kamoroso94
kamoroso94

Reputation: 1735

You had a lot of small bugs in your code. You defined the src property of the image before its onload event, which won't ensure it is fired. Your push function would run forever, but should end as soon as the image is off-screen, presumably. You also made no use of the callback you were passing into push from play. I added the callback as an argument and executed when push executes for the final time. You also had a canvas and canvasIn argument, which weren't really necessary. You hadn't even used canvasIn, but went with referring to img instead. Therefore, I removed those arguments. I also added an xOff variable to keep track of the state of the canvas to know when the animation finished.

var img = new Image();
var imgLoaded = false;
img.onload = function () {
    imgLoaded = true;
};
img.src = "http://in5d.com/wp-content/uploads/2014/11/SHMNTYMETM.jpg";
var canvas = document.querySelector("canvas");
var xOff = 0;

function play() {
    push(function () {
        console.log("done");
    });
}

function push (callback) {
    var ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.translate(5, 0);
    if (xOff < img.width) {
        if(imgLoaded) {
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        }
        xOff+=5;
        window.requestAnimationFrame(function () {
            push(callback);
        });
    } else {
        callback();
    }
}

Upvotes: 1

Related Questions