最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to display image in canvas in angular 2? - Stack Overflow

programmeradmin2浏览0评论

I have an image i am getting from a url. I want to display this image in a canvas but when it gives me error image not found but my image is present in a folder and I have given its path correclty. Tell me why it is saying image not found?

I have this in Html:

 <canvas #canvas></canvas>

Here is my ponent Code:

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";

}

}

I have an image i am getting from a url. I want to display this image in a canvas but when it gives me error image not found but my image is present in a folder and I have given its path correclty. Tell me why it is saying image not found?

I have this in Html:

 <canvas #canvas></canvas>

Here is my ponent Code:

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";

}

}
Share Improve this question edited Feb 10, 2018 at 11:51 NTP 4,4483 gold badges17 silver badges25 bronze badges asked Feb 10, 2018 at 10:39 Muhammad Naeem AkhtarMuhammad Naeem Akhtar 1821 gold badge3 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 2

Your code looks good the only issue I have found is that you have not defined the canvas variable.

@ViewChild("canvas") canvas;

WORKING DEMO

发布评论

评论列表(0)

  1. 暂无评论