灰度图像URL

我目前正在尝试使用javascript和html代码制作一个程序,您可以在其中输入图像URL,然后单击“提交”按钮,它将使用URL作为输入来对图像进行灰度处理。我遇到的问题是尝试将URL作为变量输入连接,并使用按钮创建一个函数来显示灰度图像。我失去了在这一领域的经验,所以我很抱歉如果它看起来像一个业余爱好者。如果还有我忽略且代码中未提及的问题,将不胜感激。我尝试使用具有广泛功能的示例,以便可以为程序重新创建它。

<!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>
评论