2017-03-14 5 views
1

私はキャンバスとイメージスライダでテストしていたので、このコードと次の問題で終了しました。JavaScript画像のスライダがブラウザごとに異なる

閉じた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, 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); 
}; 
+0

ありがとうございました。私はあまりに早く諦めました、私はいくつかのラインを分割することを考えましたが、私は 'インデックス'がimgだと確信していました。 –

関連する問題