I have been looking to change the colour of an image when a click event is used.
I Came across this post, which the first and main response with the Mug works really well.
However, I need to use class, rather than ID, as I need to change the colour of more than one image. When I change the code to getElementsByClassName, instead of byID, it no longer works.
I of course change the ID=mug to class=mug.
I can't see anywhere else in the code that would cause a problem, so any help would be appreciated.
I can't post on the original so adding here. Original link is: How to change color of an image using jquery
This is the code:
<img src="mug.png" id="mug" width="25%" height="25%" onload="getPixels(this)" />
<input type="text" id="color" value="#6491ee" />
<input type="button" value="change color" onclick="changeColor()">
<script type="text/javascript">
var mug = document.getElementById("mug");
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var originalPixels = null;
var currentPixels = null;
function HexToRGB(Hex)
{
var Long = parseInt(Hex.replace(/^#/, ""), 16);
return {
R: (Long >>> 16) & 0xff,
G: (Long >>> 8) & 0xff,
B: Long & 0xff
};
}
function changeColor()
{
if(!originalPixels) return; // Check if image has loaded
var newColor = HexToRGB(document.getElementById("color").value);
for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
{
if(currentPixels.data[I + 3] > 0)
{
currentPixels.data[I] = originalPixels.data[I] / 255 * newColor.R;
currentPixels.data[I + 1] = originalPixels.data[I + 1] / 255 * newColor.G;
currentPixels.data[I + 2] = originalPixels.data[I + 2] / 255 * newColor.B;
}
}
ctx.putImageData(currentPixels, 0, 0);
mug.src = canvas.toDataURL("image/png");
}
function getPixels(img)
{
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.width, img.height);
originalPixels = ctx.getImageData(0, 0, img.width, img.height);
currentPixels = ctx.getImageData(0, 0, img.width, img.height);
img.onload = null;
}
</script>
Thanks