使用JavaScript将greyscale fx添加到类中?

时间:2011-09-30 10:37:10

标签: javascript jquery html5-canvas grayscale

我正在尝试使用jQuery为每个具有类greyscale的图像添加灰度fx,但下面似乎不起作用。有没有人知道为什么这可能不起作用?

    $(function(){

        var imgObj = $('.greyscale');       
       var canvas = document.createElement('canvas');
        var canvasContext = canvas.getContext('2d');
        var imgW = imgObj.width;
        var imgH = imgObj.height;
        canvas.width = imgW;
        canvas.height = imgH;

        canvasContext.drawImage(imgObj, 0, 0);
        var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);

        for(var y = 0; y < imgPixels.height; y++){
            for(var x = 0; x < imgPixels.width; x++){
                var i = (y * 4) * imgPixels.width + x * 4;
                var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                imgPixels.data[i] = avg; 
                imgPixels.data[i + 1] = avg; 
                imgPixels.data[i + 2] = avg;
            }
        }

        canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
        return canvas.toDataURL();
 }); 

1 个答案:

答案 0 :(得分:1)

你目前所犯的错误是:

  • 绘制jQuery对象而不是画布
  • 在准备处理程序中返回数据URL,这似乎毫无意义

你应该做的是:

  • 迭代所有图像元素,为每个画布执行以下操作:
    • 制作灰度版本
    • 将图像href设置为灰度画布的数据URL

赞:http://jsfiddle.net/eGjak/140/

$(window).load(function() { // wait for images to load also
    var imgObj = $('.greyscale');
    return imgObj.each(function() {
        var canvas = document.createElement('canvas');
        var canvasContext = canvas.getContext('2d');
        var imgW = this.width;
        var imgH = this.height;
        canvas.width = imgW;
        canvas.height = imgH;

        canvasContext.drawImage(this, 0, 0);
        var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);

        for(var y = 0; y < imgPixels.height; y++){
            for(var x = 0; x < imgPixels.width; x++){
                var i = (y * 4) * imgPixels.width + x * 4;
                var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                imgPixels.data[i] = avg; 
                imgPixels.data[i + 1] = avg; 
                imgPixels.data[i + 2] = avg;
            }
        }

        canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
        console.log(canvas.toDataURL())
        this.src = canvas.toDataURL();
    });
});