简体   繁体   中英

Adding greyscale fx to a class using JavaScript?

I'm trying to use jQuery to add a greyscale fx to every image that has a class greyscale , but the below doesn't seem to work. Has anyone got any ideas on why this may not be working?

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

What you're currently doing wrong is:

  • Drawing a jQuery object and not a canvas
  • Returning a data URL inside a ready handler, which seems to be meaningless

What you should do is:

  • Iterate over all image elements, doing the following for each canvas:
    • Make a greyscale version
    • Set the image href to the data URL of the greyscale canvas

Like: 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();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM