我有一个大问题。我无法以角度从资产文件夹将图像加载到画布上。
html代码
<div class="container-fluid">
<div class="row">
<div class="col-md-8 canvas-viewer">
<canvas width="240" height="297" style="border:1px solid #d3d3d3;" id="crfCanvas" #crfCanvas></canvas>
</div>
<div class="col-md-4 canvas-anno">
</div>
</div>
</div>
component.ts代码
export class CanvasComponent implements OnInit {
@ViewChild("crfCanvas", { static: true }) crfCanvas: ElementRef;
constructor() { }
ngOnInit() {
let canvas = this.crfCanvas.nativeElement;
let ctx = canvas.getContext("2d");
let img = new Image();
img.src = "../../assets/aCRF-PRV111_CLN-001 v1.4-images/aCRF-PRV111_CLN-001 v1.4-blank_0.jpg";
ctx.drawImage(img, 10, 10, 250, 250);
}
}
答案 0 :(得分:0)
需要考虑一些事情:
ViewChild绑定到视图,因此最好等待视图完成初始化(使用ngAfterViewInit钩子),但是ngOnInit也将起作用(这就是您将来需要考虑偏移等进行绘制时)进入画布,它可能会咬你:)
图像加载是一个异步任务,您在尝试绘制图像之前需要利用onload挂钩
使用“ /assets/..”URL避免出现问题
更新的代码:
export class CanvasComponent implements OnInit {
@ViewChild("crfCanvas", { static: true }) crfCanvas: ElementRef;
constructor() { }
ngAfterViewInit() {
let canvas = this.crfCanvas.nativeElement;
let ctx = canvas.getContext("2d");
let img = new Image();
img.src = "/assets/aCRF-PRV111_CLN-001 v1.4-images/aCRF-PRV111_CLN-001 v1.4-blank_0.jpg";
img.onload = () => {
ctx.drawImage(img, 10, 10, 250, 250);
}
}
}
Stackblitz:https://stackblitz.com/edit/angular-v5tqbn