画布不渲染来自输入的图像

时间:2020-10-01 18:26:57

标签: javascript html5-canvas

嗨,我想绘制输入中插入的图像。我在图像对象中得到了正确的数据,并且可以将img作为html元素显示在正文中,但是我的画布无法呈现它。

这是我的html

        <canvas id="loadImageCanvas"></canvas>
        <input id="loadImageInput" type="file">

这是我的JavaScript

class ImageEditor{

constructor(){
    this.canvasElement = document.getElementById('loadImageCanvas');
    this.canvas = document.getElementById('loadImageCanvas').getContext('2d');
    this.imageInput = document.getElementById('loadImageInput');
    this.loadedImg = new Image();
   }

loadImage = () => {
    console.log(this.loadedImg)
    this.canvas.drawImage(this.loadedImg, 0, 0);
   }

init = () =>{
    this.canvasElement.width = 300;
    this.canvasElement.height = 300;
   }
}

$(document).ready(function(){
    $("#loadImageInput").change(function(){
        readURL(this);
    })
})

function readURL(input) {
    if (input.files && input.files[0]) {
      let reader = new FileReader();
      reader.readAsDataURL(input.files[0]); // convert to base64 string
        reader.onload = function(e) {
        imgEditor.loadedImg.src = e.target.result;
        imgEditor.canvas.drawImage(imgEditor.loadedImg, 0, 0);
        imgEditor.loadImage();
        }
    }
  }

let imgEditor = new ImageEditor();
imgEditor.init();

事实上,当我使用两个相同的事件侦听器作为输入时,我能够在画布上渲染图像,但是我并不理解为什么它不能与一个事件侦听器一起工作。

1 个答案:

答案 0 :(得分:2)

修复以下内容。图片绘制应在图片的onload回调中。

  loadImage = () => {
    console.log(this.loadedImg)
    this.loadedImg.onload = () => {
      this.canvas.drawImage(this.loadedImg, 0, 0);
    }
  }

enter image description here

相关问题