首页 > 解决方案 > 带有 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>. 这有什么关系吗?

标签: angulartypescriptcanvas

解决方案


@Kaiido 是正确的。我需要等待图像加载。我一直在使用setTimeout(e => this.draw(), 500);,直到找到更好的解决方案。


推荐阅读