如何解决画布不渲染来自输入的图像
嗨,我想绘制输入中插入的图像。我在图像对象中得到了正确的数据,并且可以将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);
}
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);
imgEditor.loadImage();
}
}
}
let imgEditor = new ImageEditor();
imgEditor.init();
事实上,当我使用两个相同的事件侦听器作为输入时,我能够在画布上渲染图像,但是我并不理解为什么它不能与一个事件侦听器一起工作。
解决方法
修复以下内容。图片绘制应在图片的onload回调中。
loadImage = () => {
console.log(this.loadedImg)
this.loadedImg.onload = () => {
this.canvas.drawImage(this.loadedImg,0);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。