Mihai Baja
Mihai Baja

Reputation: 21

JavaScript image slider acting different on each browser

I was testing with canvas and image slider so I ended up with this code and the following problem.

When I load it with from closed Firefox, I get this error on console.

IndexSizeError: Index or size is negative or greater than the allowed amount

When I refresh page it works perfectly.

On Chrome there's no way to get it running, and on Edge works well since the 1st load.

var img = [new Image(), new Image(), new Image(), new Image()];
img[0].src = 'beach.jpg';
img[1].src = 'mountain.jpg';
img[2].src = 'urban.jpg';
img[3].src = 'rural.jpg';

var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var cC = canvas.getContext('2d');
canvas.height = img[0].height;
canvas.width = img[0].width;

var ix = 0;
var nimg = Math.floor(Math.random()*4);
window.requestAnimationFrame(xx);
function xx(){
    ix++;
    if (ix > 0 && ix < 101){

        //the following line is the one that firefox throws error in console
        cC.drawImage(img[nimg], 0, 0, canvas.width*ix/100, canvas.height*ix/100, 0, 0, canvas.width*ix/100, canvas.height*ix/100);

    } else if (ix === 101){
        ix = -100;
        nimg = Math.floor(Math.random()*4);
    }
    window.requestAnimationFrame(xx);
};

Upvotes: 1

Views: 46

Answers (1)

Hasan Aslam
Hasan Aslam

Reputation: 799

This probably happens because the images are loaded asynchronously by the browser, so the canvas dimensions will be set to 0, 0 because the image hasn't loaded yet. Try loading the canvas dimensions like so:

var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var cC = canvas.getContext('2d');

var img = [new Image(), new Image(), new Image(), new Image()];
img[0].src = 'beach.jpg';
img[1].src = 'mountain.jpg';
img[2].src = 'urban.jpg';
img[3].src = 'rural.jpg';

img[0].onload = function() {
    canvas.height = this.height;
    canvas.width = this.width;
}

var ix = 0;
var nimg = Math.floor(Math.random()*4);
window.requestAnimationFrame(xx);
function xx(){
ix++;
if (ix > 0 && ix < 101){
    cC.drawImage(img[nimg], 0, 0, canvas.width*ix/100, canvas.height*ix/100, 0, 0, canvas.width*ix/100, canvas.height*ix/100);
} else if (ix === 101){
ix = -100;
nimg = Math.floor(Math.random()*4);
}
window.requestAnimationFrame(xx);
};

Upvotes: 1

Related Questions