尝试使用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();
}
}
...
}
当我做一个console.log(this.imageObj);
有时我得到<img src="../../assets/pdf.png">
其他时候我只得到<img>
。这有什么关系吗?