JS:函数在控制台中手动工作,但不会在代码中自动执行

JS: Function works manually in console but not executed automatically in code

我从这里复制了这段代码:https://codepen.io/duketeam/pen/ALEByA

此代码应该加载图片并在单击按钮后将其设为灰度。 我想更改代码,使图片立即以灰度显示而无需单击按钮,因此我将其注释掉并将 makeGray() 包含在 <input...> 的加载部分中。但这不起作用。我哪里错了?

我试图省略 makeGray() 并仅上传图片并在控制台中键入 makeGray() 并且它的工作非常好,但我需要它自动执行。我还尝试将 makeGray() 函数中的所有代码都放在 upload() 函数中,但在这里它也不会触发。

var image = null;

function upload() {
  //Get input from file input
  var fileinput = document.getElementById("finput");
  //Make new SimpleImage from file input
  image = new SimpleImage(fileinput);
  //Get canvas
  var canvas = document.getElementById("can");
  //Draw image on canvas
  image.drawTo(canvas);

}

function makeGray() {
  //change all pixels of image to gray
  for (var pixel of image.values()) {
    var avg = (pixel.getRed() + pixel.getGreen() + pixel.getBlue()) / 3;
    pixel.setRed(avg);
    pixel.setGreen(avg);
    pixel.setBlue(avg);
  }
  //display new image
  var canvas = document.getElementById("can");
  image.drawTo(canvas);
}
<script src="https://www.dukelearntoprogram.com/course1/common/js/image/SimpleImage.js">
</script>

<h1>Convert Image to Grayscale</h1>

<canvas id="can"></canvas>

<p>
  <input type="file" multiple="false" accept="image/*" id="finput" onchange="upload();makeGray()">

</p>
<p>
  <!---- <input type="button" value="Make Grayscale" onclick="makeGray()" -->
</p>
<script src="./index.js"></script>

有些事情您需要等待,但我不确定具体是什么。如果将函数包装在 setTimeout 中,它可以正常工作。对于系统较慢或文件较大的客户端,您可能 想要多等几毫秒。如果您弄清楚什么需要花费一些时间,为了安全起见,您可以改用 .thenawait

var image = null;

function upload() {
  //Get input from file input
  var fileinput = document.getElementById("finput");
  //Make new SimpleImage from file input
  image = new SimpleImage(fileinput);
  //Get canvas
  var canvas = document.getElementById("can");
  setTimeout(() => {
    //change all pixels of image to gray
    for (var pixel of image.values()) {
      var avg = (pixel.getRed() + pixel.getGreen() + pixel.getBlue()) / 3;
      pixel.setRed(avg);
      pixel.setGreen(avg);
      pixel.setBlue(avg);
    }
    image.drawTo(canvas);
  }, 100);
}
<script src="https://www.dukelearntoprogram.com/course1/common/js/image/SimpleImage.js">
</script>

<h1>Convert Image to Grayscale</h1>

<canvas id="can"></canvas>

<p>
  <input type="file" multiple="false" accept="image/*" id="finput" onchange="upload();">

</p>
<script src="./index.js"></script>