0

I want to use canvas to make an image to grayscale. There are a number of examples. But it has problem with my latest Chrome and Firefox. Surprisingly, IE9 is good. Is it the problem of my code?

And here is my code:

function draw() {
canvas = document.getElementById('canvas')
ctx = canvas.getContext('2d');
image = new Image();
image.src = 'ichiro.jpg';
ctx.drawImage(image, 0, 0);
imgd = ctx.getImageData(0, 0, 480, 400);
for (i=0; i<imgd.data.length; i+=4) {
    grays = imgd.data[i]*.3 + imgd.data[i+1]*.6 + imgd.data[i+2]*.1;
    imgd.data[i  ] = grays;   // red
    imgd.data[i+1] = grays;   // green
    imgd.data[i+2] = grays;   // blue
}
ctx.putImageData(imgd, 0, 0);

imggray = new Image();
imggray.src = canvas.toDataURL();
imggray.onload = function() {
    ctx.drawImage(imggray, 0, 0);
}

}

I am new to HTML5 and javascript. So any help will be appreciated.

4

1 回答 1

0

编辑:

对不起,我看错了你的问题。几乎可以肯定是因为安全错误。getImageData如果您在画布上绘制了来自不同“来源”(不同域或本地文件系统)的图像,则不允许使用。在本地 Chrome 中,如果你这样做,你可以绕过它:

C:\Users\root\AppData\Local\Google\Chrome\Application\chrome.exe --allow-file-access-from-files

有一种叫做 origin-clean 标志的东西,一旦你从不同的来源绘制图像,它就会被删除。出于(良好的)安全原因,所有文件的来源都不同。


原答案:

您需要等待图像加载:

工作示例:http: //jsfiddle.net/SYLW2/1107/

...
// this now happens only after the image is loaded:
image.onload = function() {
ctx.drawImage(image, 0, 0);
imgd = ctx.getImageData(0, 0, 480, 400);
for (i=0; i<imgd.data.length; i+=4) {
    grays = imgd.data[i]*.3 + imgd.data[i+1]*.6 + imgd.data[i+2]*.1;
    imgd.data[i  ] = grays;   // red
    imgd.data[i+1] = grays;   // green
    imgd.data[i+2] = grays;   // blue
}
ctx.putImageData(imgd, 0, 0);

imggray = new Image();
imggray.src = canvas.toDataURL();
imggray.onload = function() {
    ctx.drawImage(imggray, 0, 0);
}
}
image.src = 'http://placekitten.com/400/400';
于 2011-10-21T00:37:54.700 回答