如何在角度2的画布中显示图像?

时间:2018-02-10 10:39:38

标签: javascript angular canvas

我有一个来自网址的图片。我想在画布中显示这个图像但是当它给我错误图像时找不到但是我的图像存在于一个文件夹中并且我给它的路径相关。告诉我为什么说找不到图像?

我在Html中有这个:

 <canvas #canvas></canvas>

这是我的组件代码:

export class drawingTestFormComponent{
@Input() public width = 495;
@Input() public height = 445;

private cx: CanvasRenderingContext2D;

public ngAfterViewInit() {
    const canvasEl: HTMLCanvasElement = this.canvas.nativeElement;
    this.cx = canvasEl.getContext('2d')!;
    let image = new Image();


    canvasEl.width = this.width;
    canvasEl.height = this.height;

    this.cx.lineWidth = 3;
    this.cx.lineCap = 'round';
    this.cx.strokeStyle = '#000';
    image.onload = ()=> {
        this.cx.drawImage(image, 0, 0, this.width, this.height);
    }
    image.src = "../../../../wwwroot/dist/assets/blackBoards/NCAA_mhalfcourt_500x410.png";

}

}

1 个答案:

答案 0 :(得分:0)

您的代码看起来不错,我发现的唯一问题是您没有定义canvas变量。

@ViewChild("canvas") canvas;

<强> WORKING DEMO