I'm currently trying to make a program with javascript and html codes where you can input an image URL and with the click of the submit button, it will grayscale the image using the URL as the input. The problems I'm having is trying to connect the the URL as a variable input and creating a function with the button to display the grayscale image. I lost my experience in this field so I do apologize if it looked like an amateur made this. If there's anymore problems that I overlooked and didn't mention in the code, any help will be greatly appreciated. I tried using examples for broad functions so I can recreate it for my program.
<!DOCTYPE html>
<html>
<head>
<style>
var imgObj = document.getElementById('js-image');
function gray(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();
}
var image = document.getElementById("img");
var imageSrc = image.getAttribute("src");
image.setAttribute("src", imageSrc + randomNumber);
</style>
</head>
<body>
<p>Insert image URL: <input type="img" src=img></p>
<button onclick=button;">Submit</button>
<script>
function button() {
var x = document.getElementById("imgObj");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>