Javascript canvas 的像素操作,模糊滤镜不起作用

Javascript pixel manipulation of canvas, Blur filter not working

我目前正在 canvas 开发一个简单的绘图板网站。

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

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

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

感谢您的宝贵时间。

您需要偏移您从过滤器循环中读取的坐标,否则您每次都会从相同的像素读取(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];

    }
}