I have this piece of code that runs a function to transform a color image with the class=”gray” to gray scale.
$(document).ready(function(){
$('.gray').click(function(){
this.src = grayscale(this.src);
});
});
function grayscale(img){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var imgObj = new Image();
imgObj.src = img;
canvas.width = imgObj.width;
canvas.height = imgObj.height;
ctx.drawImage(imgObj, 0, 0);
var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
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;
}
}
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
}
This works OK with the click function, but I want that color image to become gray scaled immediately right after the page is loaded, so the function must run without the click. How to do this?
You can substitute
clickwitheach.