JavaScript 图像 slider 在每个浏览器上的作用不同

标签 javascript browser

我正在使用 Canvas 和图像 slider 进行测试,所以我最终得到了这段代码和以下问题。

当我从关闭的 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);
};

最佳答案

发生这种情况的原因可能是浏览器异步加载图像,因此 Canvas 尺寸将设置为 0, 0 因为图像尚未加载。尝试像这样加载 Canvas 尺寸:

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

关于JavaScript 图像 slider 在每个浏览器上的作用不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42797579/

相关文章:

javascript - 未捕获的语法错误 : Unexpected token < (anonymous function) on console

jquery - 使用jquery addClass和removeClass时浏览器重画非常慢

javascript - 如何从其他浏览器重定向到 IE?

html - 在 iOS7 中固定页眉和页脚的网页滚动问题

javascript - VueJS 中的 AJAX 数据更新后 DOM 不更新

javascript - 加载时的窗口调度事件不适用于内联脚本

javascript - 国际化翻译 fnando

javascript - 查找 div 子级中的文本长度

browser - 本地主机与机器名称的 CSS 样式不同

javascript - 我可以查看浏览器的事件循环来了解 JS 的执行顺序吗?