What I have is a little jQuery based script intended to grayscale an image.
It works, but I have a big issue with picking the event that will trigger it.
I need it to simply be automatically triggered, once, when image is loaded. Now, this:
imgObj.ready
works perfectly in IE, in Firefox it’s a gamble on each refresh, and in Safari/Chrome/Opera not at all.
This however:
imgObj.click
works great in all browsers, but I need it to happen automatically, without clicking.
(or with emulated click, but I didn’t manage to make it, anyone knows how?)
And finally this:
imgObj.load
works “too good” – it works in all browsers, but keeps re-executing the function over and over – I tried putting a variable inside a function to make it be executed just once, but it didn’t work, .load keeps re-executing.
Sorry for the long post, and thanks very much for reading through – below is the full code.
var imgObj = $('#image');
imgObj.click(function(){
var imgObj = document.getElementById('image');
if($.browser.msie){
grayscaleImageIE(imgObj);
} else {
imgObj.src = grayscaleImage(imgObj);
}
});
function grayscaleImageIE(imgObj)
{
imgObj.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)';
}
function grayscaleImage(imgObj)
{
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();
}
How about this?