I used canvas to change the color (this case to grayscale) of the images on a web page. However, only the last image is changed, by using the following code.
But I want to CHANGE THE COLOR of ALL IMAGES on a WEB PAGE
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(function(){
var theImages = [];
var myImages = [];
var theChanged = [];
theImages = document.getElementsByTagName("img");
theChanged = document.getElementsByTagName("img");
// create a temporary canvas to put the original image
var tempCanvas=document.createElement("canvas");
var tempCtx=tempCanvas.getContext("2d");
for (var i=0; i <theImages.length; i++){
myImages[i] = theImages [i];
tempCtx.drawImage(myImages[i],myImages[i].width,myImages[i].height);
var newImage=new Image();
newImage.onload=function(){
// call function to replace red with green
recolorImage(newImage,i, theChanged);
}
newImage.src= myImages[i].src;
}
function recolorImage(img_to_change, number, img_changed){
var newCanvas = document.createElement('canvas');
var ctx = newCanvas.getContext("2d");
var theWidth = img_to_change.width;
var theHeight = img_to_change.height;
newCanvas.width = theWidth;
newCanvas.height = theHeight;
// draw the image on the temporary canvas
ctx.drawImage(img_to_change, 0, 0, theWidth, theHeight);
// pull the entire image into an array of pixel data
var imageData = ctx.getImageData(0, 0, theWidth, theHeight);
// CHANGE OF THE COLOR PIXELS
for (var y = 0; y < theHeight; y ++) {
for (var x = 0; x < theWidth; x ++) {
offset = ((y*(theWidth*4)) + (x*4));
imageData.data[offset + 0] = Math.round((imageData.data[offset + 0] +imageData.data[offset + 1] +imageData.data[offset + 2] )/3);
imageData.data[offset + 1] = imageData.data[offset + 0];
imageData.data[offset + 2] = imageData.data[offset + 0];
} //for
} //for
// final of the CHANGE OF THE PIXEL COLOR
//------------------------------------------------------------------------------------------------------------------
// put the altered data back on the canvas
ctx.putImageData(imageData,0,0);
// put the re-colored image back on the image
var finalImag = img_changed[number-1];
finalImag.src = newCanvas.toDataURL();
}
}); // end $(function(){});
</script>
<body>
<p>First Image</p>
<img src="imagens_250x180/rosa.jpg" name="image0" width=250 height=180 ><br/>
<p>Second Image</p>
<img src="imagens_250x180/ricardina.jpg" name="image1" width=250 height=180 >
<p>Third Image</p>
<img src="imagens_250x180/manaus.jpg" name="image2" width=250 height=180 >
</body>
</html>