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 = im开发者_Python百科gObj.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();
});
});
精彩评论