angular - 带有 Canvas drawImage 的 Angular 5 未显示
问题描述
尝试使用 drawImage 将背景图像添加到画布并且它没有显示出来。我知道图像的路径是正确的,因为我可以做到<img src="{{ imageName }}" />
并且有效。其他一切在 JavaScript 中都可以正常工作,但不能很好地转换为 Angular。
HTML:
<canvas #canvas></canvas>
打字稿:
import { Component, OnInit } from '@angular/core';
...
@Component({
selector: 'app-box-picker',
templateUrl: './box-picker.component.html',
styleUrls: ['./box-picker.component.css']
})
export class BoxPickerComponent implements OnInit {
@ViewChild('canvas') public canvas: ElementRef;
canvasEl: any;
ctx: CanvasRenderingContext2D;
@Input() public width = 535.0;
@Input() public height = 669.25;
mousePosition: any;
isMouseDown: boolean;
dragoffx: number;
dragoffy: number;
circles: any;
imageObj = new Image();
imageName = "../../assets/pdf.png";
constructor() {
}
ngOnInit() {
}
public ngAfterViewInit() {
this.canvasEl = this.canvas.nativeElement;
this.ctx = this.canvasEl.getContext('2d');
this.canvasEl.width = this.width;
this.canvasEl.height = this.height;
this.imageObj.src = this.imageName;
console.log(this.imageName);
console.log(this.imageObj);
// init circles
var c1 = new Circle();
c1.init(50, 50, 15, "rgba(217,83,79, .5)", "black", this.ctx);
// console.log(c1);
c1.out();
this.circles = [c1];
this.draw();
this.captureDownEvents(this.canvasEl);
this.captureMoveEvents(this.canvasEl);
this.captureUpEvents(this.canvasEl);
}
draw() {
//clear canvas
this.ctx.clearRect(0, 0, this.canvasEl.width, this.canvasEl.height);
this.ctx.drawImage(this.imageObj, 0, 0, this.canvasEl.width, this.canvasEl.height);
this.drawCircles();
}
drawCircles() {
for (var i = this.circles.length - 1; i >= 0; i--) {
this.circles[i].draw();
}
}
...
}
当我做 a时,console.log(this.imageObj);
有时我得到<img src="../../assets/pdf.png">
,而其他时候我只得到<img>
. 这有什么关系吗?
解决方案
@Kaiido 是正确的。我需要等待图像加载。我一直在使用setTimeout(e => this.draw(), 500);
,直到找到更好的解决方案。
推荐阅读
- java - System.out.printf() 用法
- php - PHP 会话以不同的方式工作 xampp 和 web
- node.js - 如何避免在云存储事件的文件夹上执行 firebase 功能
- java-9 - java9:使用 jlink 的 IllegalArgumentException
- java - 触发 MQTT 代理使用 Paho Java 客户端发布遗嘱消息
- r - 使用 purrr::pmap 来利用 .f 列表名称
- java - Spring Boot:是否有类似的方法来保存字符串的 XML 资源并像在 Androids 框架中一样引用它们?
- python - 将 SAV 转换为 CSV
- ios - Swift将导航栏标题更改为所选表格视图单元格的标题
- javascript - 从 json 数组中获取结果