Javascript canvas drawImage 结果为空白? -修改-

Javascript canvas drawImage results in blank? -revised-

我在 lit-element 组件内部工作,试图将 img 元素绘制到 canvas 元素上:

return html` 
  <img></img>
  <br>
  <canvas width="1500" height="1500"></canvas>
  <br>
  <input type='file' accept='image/*' @change=${this.readImage}> </input>
`
  readImage(event) {
    // Get the image element
    var img = this.shadowRoot.querySelector('img')
    // Get the file
    var file = event.target.files[0]
    // File reader
    var reader = new FileReader()
    // Handle read
    reader.onload = event=>{
       img.src = event.target.result
       // Get the canvas element
       var canvas = this.shadowRoot.querySelector('canvas')
       // Get the canvas context
       var context = canvas.getContext('2d')
       // Draw image on canvas
       context.drawImage(img,0,0)
    }
    // Read the file
    reader.readAsDataURL(file)
  }

然而,由于某种原因,canvas 元素仍为空白。我无法找出我哪里出错了,或者我是否 运行 遇到了某种错误?

您需要使用 onload 来确保图像已完成加载。您不只是使用 new Image() 对象而不是使用嵌入式 img 元素的原因是什么?

this.shadowRoot=document;

function
readImage(event) {
  // Get the image element
  var img = this.shadowRoot.querySelector('img')
  // Get the file
  var file = event.target.files[0]
  // File reader
  var reader = new FileReader()
  // Handle read
  reader.onload = event => {
    img.onload = () => {
      // Get the canvas element
      var canvas = this.shadowRoot.querySelector('canvas')
      // Get the canvas context
      var context = canvas.getContext('2d')
      // Draw image on canvas
      context.drawImage(img, 0, 0)
    }

    img.src = event.target.result
  }
  // Read the file
  reader.readAsDataURL(file)
}
<img></img>
<br>
<canvas width="1500" height="1500"></canvas>
<br>
<input type='file' accept='image/*' onchange=readImage(event)> </input>