I am new to js and here I have a function changeColor()
that I want to change the color of an image when a button is clicked, but it seems the function is not defined. Someone help?
Here is just a simple button in html, and I want to change img's color by clicking button:
<script src="{% static 'js/color_change.js' %}" type="text/javascript"></script>
<div class="container">
<div id="colorpicker"></div>
<img src="../media/colortest2.png" id="mug" width="5000" height="5000"
onload="getPixels(this)"/>
<button name="color" value="#33FFBD" type="button" onclick="changeColor();">
Change
</button>
</div>
My js file, I want to get the value of the button and change to specified color for the img:
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var originalPixels = null;
var currentPixels = null;
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;
}
function hexToRGB(hex)
{
var long = parseInt(hex.replace(/^#/, ""), 16);
return {
R: (long >>> 16) & 0xff,
G: (long >>> 8) & 0xff,
B: long & 0xff
};
}
Object.onclick = function changeColor()
{
var mug = document.getElementById("mug");
if(!originalPixels) return; // Check if image has loaded
var newColor = hexToRGB(document.getElementByName("color").value);
for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
{
if(currentPixels.data[I + 3] > 0) // If it's not a transparent pixel
{
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");
}