我正在使用 typescript 将用户上传的图像设置为 Canvas 背景。但是,我猜由于一些绑定(bind)问题,它仅在用户上传文件两次时才有效。在尝试将其设置为 Canvas 背景之前如何等待图像加载?
我尝试仅在 selectedFile
变量不为 null 时运行 Canvas 代码(见下文),但我收到了相同的错误。
<input type="file" (change)="onFileChanged($event)">
<canvas id="canvas"></canvas>
private selectedFile: File = null;
private imgURL: any;
onFileChanged(event){
if(event.target.files.length == 0) return;
this.selectedFile = <File> event.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(this.selectedFile);
reader.onload = (_event) => {this.imgURL = reader.result;}
var canvas : any = document.getElementById("canvas");
var ctxt = canvas.getContext("2d");
var background = new Image();
background.src = this.imgURL;
background.onload = function () {
ctxt.drawImage(background, 0, 0, canvas.width, canvas.height);
};
}
我希望 Canvas 将所选图像显示为背景。但是,用户第一次上传图像时,输出为 GET http://localhost:4200/undefined 404 (Not Found) Image (async)
。当用户上传不同的图像时,背景将更新为第一个选定的图像。
最佳答案
我认为您需要做的就是将 Canvas 代码放入 reader.onload
回调中。
onFileChanged(event) {
if (event.target.files.length == 0) return;
this.selectedFile = < File > event.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(this.selectedFile);
reader.onload = (_event) => {
this.imgURL = reader.result;
var canvas: any = document.getElementById("canvas");
var ctxt = canvas.getContext("2d");
var background = new Image();
background.src = this.imgURL;
background.onload = function() {
ctxt.drawImage(background, 0, 0, canvas.width, canvas.height);
};
}
}
您可能会收到错误,因为您的 .onload
异步回调尚未触发,并且当您尝试时 this.imgURL
将是 undefined
使用它。现在,它会等到我们获得 imgURL 的值后再尝试使用它。
关于html - 如何立即将上传的图像显示为 Canvas 背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56139989/