JavaScript图像滑块在每个浏览器上表现不同

时间:2017-03-14 22:15:21

标签: javascript browser

我正在测试画布和图片滑块,所以我最终得到了这段代码和以下问题。

当我从关闭的Firefox加载它时,我在控制台上收到此错误。

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

当我刷新页面时,它完美无缺。

在Chrome上,没有办法让它运行,并且自第一次加载以来,Edge运行良好。

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);
};

1 个答案:

答案 0 :(得分:1)

这可能是因为图像是由浏览器异步加载的,因此画布尺寸将设置为0, 0,因为图像尚未加载。尝试加载画布尺寸,如下所示:

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);
};