猿问

火狐报错 Index or size is negative...

问题描述

利用canvas改变图片的颜色, 谷歌运行正常, 火狐报错

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


问题出现的环境背景及自己尝试过哪些方法

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

revertColor(type) {


    let config = {

        attention: {

            url: this.local.myAttention.map(it => it.dataIconUrl),

            className: '.myAttention-icon',

            size: 32,

            padding: 4

        },

        dataProduct: {

            url: this.local.dataProductList.map(it => it.productIcon),

            className: '.dataProduct-icon',

            size: 45.6,

            padding: 0

        }

    };

    let {url, className, size, padding} = config[type];


    size = Math.floor(size)



    url = url.slice(0, 8);


    (Array.from($(className)) || []).forEach((node, idx) => {

        let canvas = node.getContext('2d');

        let img = new Image();

        img.src = url[idx];


        img.onload = function () {

            canvas.drawImage(img, padding, padding, size, size);


            let imgData = canvas.getImageData(padding, padding, img.width, img.height) || {};

            let colorData = imgData.data;


            for (let i = 0; i < colorData.length; i += 4) {

                if (!(colorData[i] === 75 && colorData[i + 1] === 164 && colorData[i + 2] === 190)) {

                    // 将除底色以外的所有颜色重置

                    colorData[i] = 255;

                    colorData[i + 1] = 255;

                    colorData[i + 2] = 255;


                }


            }

            canvas.clearRect(0, 0, $(className).width(), $(className).height()); 


            canvas.putImageData(imgData, padding, padding);

        }

    });


}

你期待的结果是什么?实际看到的错误信息又是什么?

火狐浏览器发现图片根本没有被绘制上去, 应该是drawImage的时候就已经出问题了


梵蒂冈之花
浏览 470回答 1
1回答

胡子哥哥

drawImage之前做一下判断~if (w > _config.canvasWidth) w = _config.canvasWidth;if (h > _config.canvasHeight) h = _config.canvasHeight;_cache.ctx.drawImage(_cache.canvas, 0, 0, w, h,                      0, 0, _config.canvasWidth, _config.canvasHeight);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答