Javascript像素操纵画布,Blur过滤器无法正常工作

时间:2015-05-28 02:10:49

标签: javascript canvas filter pixel

我目前正在使用画布上的简单绘图板网站。

http://webbox.cs.du.edu/~ansbashe/My_Art/myart.html

我想用这个javascript代码模糊画布(在webworker中)。问题是返回的数据用原始图片填充画布而不是我期望的模糊图像。我能做些什么来获得我想要的结果吗?

var  filter =   [   [1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1]];

var factor = 1/9; 
var bias = 0; 

var w = 890;
var h = 400;
function filts() {

    filt = 0;
    for(var x = 0; x < w;  x++)
    {
        for(var y = 0; y < h; y++)
        {
            var r = 0;
            var g = 0;
            var b = 0;
            var imgX = ((x - Math.floor(filter.length/2)+filterX + w) % w);
            var imgY = ((y - Math.floor(filter.length/2)+filterY + h)%h);

            for(var filterX = 0; filterX < filter.length; filterX++) {
                for(var filterY =0; filterY < filter.length; filterY++) {


                    r += imgData.data[imgX*4 + imgY * w * 4] * filter[filterY][filterX];
                    g += imgData.data[imgX*4 + imgY*w*4 + 1] * filter[filterY][filterX];
                    b += imgData.data[imgX*4 + imgY*w*4 + 2] * filter[filterY][filterX];

                }
            }
            var index = (x + (y * w)) * 4;
            retData.data[imgX*4 + imgY*w*4] = Math.min(Math.max(Math.floor(factor *r + bias),0),255);
            retData.data[imgX*4 + imgY*w*4 + 1] = Math.min(Math.max(Math.floor(factor *g + bias),0),255);
            retData.data[imgX*4 + imgY*w*4 + 2] = Math.min(Math.max(Math.floor(factor *b + bias),0),255);
            retData.data[imgX*4 + imgY*w*4 + 3] = imgData.data[imgX*4 + imgY*w*4 + 3];

        }
    }
    postMessage({img: retData});
}

感谢您的时间。

1 个答案:

答案 0 :(得分:3)

你需要在滤波器循环中偏移你正在读取的坐标,否则你每次都会从同一个像素读取(imgX,imgY):

for(var filterX = 0; filterX < filter.length; filterX++) {
    var filterImgX = (imgX + filterX) % w;
    for(var filterY =0; filterY < filter.length; filterY++) {            
        var filterImgY = (imgY + filterY) % h;

        r += imgData.data[filterImgX*4 + filterImgY * w * 4] * filter[filterY][filterX];
        g += imgData.data[filterImgX*4 + filterImgY*w*4 + 1] * filter[filterY][filterX];
        b += imgData.data[filterImgX*4 + filterImgY*w*4 + 2] * filter[filterY][filterX];

    }
}