Javascript更改图像颜色IndexSizeError:索引或大小为负数或大于允许的数量 [英] Javascript changing image color IndexSizeError: Index or size is negative or greater than the allowed amount

查看:2485
本文介绍了Javascript更改图像颜色IndexSizeError:索引或大小为负数或大于允许的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写一个javascript代码,其中图像更改颜色由用户指定..代码是从我的边完成..但奇怪的是,mozilla抛出错误 IndexSizeError:索引或大小是负或大于允许的量清除缓存时,下一次它运行良好..在chrome它不会运行..它说未捕获SecurityError:无法执行'getImageData' 'CanvasRenderingContext2D':画布已被跨原始数据污染。



我不知道什么似乎是我的问题3 4小时调试,但我不能。所以我不得不来这里。



请让我知道如果它的一个错误,可以解决。



CODE:

 < ul& 
< li>
< img src =mug.pngid =mug_imageclass =the_imagewidth =200>
< input type =textid =mug_colorvalue =#6491ee>
< input type =buttonvalue =change colorclass =changeColorButtonid =mug_button>< / li>
< li>
< img src =rug.pngid =rug_imageclass =the_imagewidth =200>
< input type =textid =rug_colorvalue =#6491ee>
< input type =buttonvalue =change colorclass =changeColorButtonid =rug_button>
< / li>
< li>
< img src =rug.pngid =nug_imageclass =the_imagewidth =200>
< input type =textid =nug_colorvalue =#6491ee>
< input type =buttonvalue =change colorclass =changeColorButtonid =nug_button>
< / li>
< / ul>
< script type =text / javascript>
$(document).ready(function(){//开始范围函数
var originalPixels = [];
var currentPixels = [];
var the_images = $(' .the_image');
var canvas = [];
var ctx = [];
$ .each(the_images,function(ind,val){
var get_id = $ (this).attr('id');
var the_id_arr = get_id.split('_');
the_id = the_id_arr [0];
canvas [the_id] = document.createElement ('canvas');
ctx [the_id] = canvas [the_id] .getContext(2d);
originalPixels [the_id] ='0';
currentPixels [the_id] 0';
getPixels(canvas [the_id],ctx [the_id],the_id,val);
});

$('。changeColorButton')。 (){
var button_id = $(this).attr('id');
var the_id_arr = button_id.split('_');
var the_id = the_id_arr [0];
var the_image = $('#'+ the_id +'_image');
var the_color = the_id +'_color';
changeColor(canvas [the_id],ctx [the_id],originalPixels [the_id],currentPixels [the_id],the_image.get(0),the_color);
});

函数HexToRGB(Hex)
{
var Long = parseInt(Hex.replace(/ ^#/,),16);
return {
R:(Long>>> 16)& 0xff,
G:(Long>>> 8)& 0xff,
B:Long& 0xff
};
}

function changeColor(canvas,ctx,originalPixels,currentPixels,obj,color_id)
{

if(!originalPixels)
返回; //检查映像是否已加载
var newColor = HexToRGB(document.getElementById(color_id).value);
for(var I = 0,L = originalPixels.data.length; I {
if(currentPixels.data [I + 3] 0)
{
currentPixels.data [I] = originalPixels.data [I] / 255 * newColor.R;
currentPixels.data [I + 1] = originalPixels.data [I + 1] / 255 * newColor.G;
currentPixels.data [I + 2] = originalPixels.data [I + 2] / 255 * newColor.B;
}
}
ctx.putImageData(currentPixels,0,0);
obj.src = canvas.toDataURL(image / png);
}

function getPixels(canvas,ctx,the_id,img)
{
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0,img.naturalWidth,img.naturalHeight,0,0,img.width,img.height);
originalPixels [the_id] = ctx.getImageData(0,0,img.width,img.height);
currentPixels [the_id] = ctx.getImageData(0,0,img.width,img.height);
img.onload = null;
}
});
< / script>

编辑:主要问题现在是未捕获SecurityError:无法执行'getImageData 'on'CanvasRenderingContext2D':画布已被跨原始数据污染。

解决方案

p>您最有可能从本地 file:// 协议或从外部网站加载图像。



浏览器会认为这是与相关的安全风险, /en.wikipedia.org/wiki/Cross-origin_resource_sharingrel =nofollow> CORS (跨源资源共享),并会抛出一个错误,因为我们不允许操纵像素缓冲区由于安全使用 getImageData() toDataURL()



必须作为解决方案在localhost / 127.0.0.1地址运行您的页面。如果您还没有安装简单的轻量级服务器,例如 Mongoose 。 / p>

如果您已经做过(或使用类似的东西),那么您需要通过向图片标签添加此属性来请求图片的跨源使用:

 < img src =...... crossOrigin =anonymous/> 

对于这个工作,服务器在另一端必须接受它通过提供特殊的头(它需要在服务器上配置,如果没有)。如果没有,或者您没有访问远程服务器,您将无法使用图像用于此目的,而不是通过您的服务器上的页面代理加载它们。


I am writing a javascript code where image changes color specified by a user.. the code is complete from my side.. but strangely mozilla throw the error IndexSizeError: Index or size is negative or greater than the allowed amount when cleared the cache and next time it runs good.. on chrome it does not run at all .. it says Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': the canvas has been tainted by cross-origin data.

Im not sure what seems to be the problem as i had spent 3 4 hours debugging it, but i couldn't. So i had to come here..

please let me know if its a error that can be solved.

CODE:

    <ul>
        <li>
            <img src="mug.png" id="mug_image" class="the_image" width="200">
            <input type="text" id="mug_color" value="#6491ee">
            <input type="button" value="change color" class="changeColorButton" id="mug_button"></li>
        <li>
            <img src="rug.png" id="rug_image" class="the_image" width="200">
            <input type="text" id="rug_color" value="#6491ee">
            <input type="button" value="change color" class="changeColorButton" id="rug_button">
        </li>
        <li>
            <img src="rug.png" id="nug_image" class="the_image" width="200">
            <input type="text" id="nug_color" value="#6491ee">
            <input type="button" value="change color" class="changeColorButton" id="nug_button">
        </li>
    </ul>
    <script type="text/javascript">
       $(document).ready(function(){ // Begin scoping function
            var originalPixels = [];
            var currentPixels = [];
            var the_images = $('.the_image');
            var canvas = [];
            var ctx = [];
            $.each(the_images, function(ind, val) {
                var get_id = $(this).attr('id');
                var the_id_arr = get_id.split('_');
                the_id = the_id_arr[0];
                canvas[the_id] = document.createElement("canvas");
                ctx[the_id] = canvas[the_id].getContext("2d");
                originalPixels[the_id] = '0';
                currentPixels[the_id] = '0';
                getPixels(canvas[the_id], ctx[the_id], the_id, val);
            });

            $('.changeColorButton').click(function() {
                var button_id = $(this).attr('id');
                var the_id_arr = button_id.split('_');
                var the_id = the_id_arr[0];
                var the_image = $('#' + the_id + '_image');
                var the_color = the_id + '_color';
                changeColor(canvas[the_id], ctx[the_id], originalPixels[the_id], currentPixels[the_id], the_image.get(0), the_color);
            });

            function HexToRGB(Hex)
            {
                var Long = parseInt(Hex.replace(/^#/, ""), 16);
                return {
                    R: (Long >>> 16) & 0xff,
                    G: (Long >>> 8) & 0xff,
                    B: Long & 0xff
                };
            }

            function changeColor(canvas, ctx, originalPixels, currentPixels, obj, color_id)
            {

                if (!originalPixels)
                    return; // Check if image has loaded
                var newColor = HexToRGB(document.getElementById(color_id).value);
                for (var I = 0, L = originalPixels.data.length; I < L; I += 4)
                {
                    if (currentPixels.data[I + 3] > 0)
                    {
                        currentPixels.data[I] = originalPixels.data[I] / 255 * newColor.R;
                        currentPixels.data[I + 1] = originalPixels.data[I + 1] / 255 * newColor.G;
                        currentPixels.data[I + 2] = originalPixels.data[I + 2] / 255 * newColor.B;
                    }
                }
                ctx.putImageData(currentPixels, 0, 0);
                obj.src = canvas.toDataURL("image/png");
            }

            function getPixels(canvas, ctx, the_id, img)
            {
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.width, img.height);
                originalPixels[the_id] = ctx.getImageData(0, 0, img.width, img.height);
                currentPixels[the_id] = ctx.getImageData(0, 0, img.width, img.height);
                img.onload = null;
            }
        });
    </script>

EDIT : the main prob now is Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': the canvas has been tainted by cross-origin data. on chrome.

解决方案

You are most likely either loading the images from a local "file://" protocol or from an external site. If the code you present contains the actual link references you are probably doing the former.

The browser will consider this a security risk related to CORS (cross-origin resource sharing) and will throw an error as we are not allowed to manipulate the pixels buffers due to security using getImageData() and toDataURL().

You must as a solution run your page at a localhost/127.0.0.1 address. If you haven't already you can install a simple light-weight server such as Mongoose.

If you already do (or using something similar) then you need to request cross-origin use for the image by adding this attribute to the image tag:

<img src="..." ... crossOrigin="anonymous" />

For this to work the server at the other end must accept this use which it does by providing special headers (which you need to configure at the server if not). If it doesn't or you don't have access to the remote server, you won't be able to use the images for this purpose other than loading them through a page proxy on your server.

这篇关于Javascript更改图像颜色IndexSizeError:索引或大小为负数或大于允许的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆