Javascript canvas drawImage的结果是空白?-修改后的

问题描述 投票:0回答:1

我在一个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元素一直是空白的。我不知道是哪里出了问题,还是我遇到了什么错误?

javascript canvas drawimage lit-element
1个回答
0
投票

你需要使用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>
© www.soinside.com 2019 - 2024. All rights reserved.