2017-03-14 8 views
1

Ich habe mit Leinwand und Bild-Slider getestet, so dass ich mit diesem Code und das folgende Problem endete.JavaScript-Bild-Slider wirkt sich auf jeden Browser anders

Wenn ich es mit geschlossenem Firefox lade, bekomme ich diesen Fehler auf der Konsole.

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

Wenn ich Seite aktualisieren, funktioniert es perfekt.

Auf Chrome gibt es keine Möglichkeit, es zu laufen, und auf Edge funktioniert gut seit dem ersten Laden.

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

Antwort

1

Dies geschieht wahrscheinlich, weil die Bilder asynchron vom Browser geladen werden, so werden die Leinwände Dimensionen 0, 0 eingestellt werden, da das Bild noch nicht geladen ist. Versuchen Sie, die Leinwandmaße wie folgt zu laden:

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

Vielen Dank für die klare und schnelle Antwort. Ich gab zu früh auf, ich dachte daran, die Linie in ein paar zu teilen, aber ich war sicher, dass der 'Index' der IMG's war. –

Verwandte Themen