angular2在变化检测后在画布上绘制图像

angular2 drawImage on canvas after change detetion

本文关键字:绘制 图像 变化检测 angular2      更新时间:2023-09-26

我有一个angelar2组件:

@Component({
    selector: 'my-image',
    template: `
    <img #img src="{{src}}" style='display: none;' />
    <canvas #canvas width="{{width}}" height="{{height}}"></canvas>`
})
export class ImageComponent implements AfterViewInit {
    @ViewChild('canvas') canvas: ElementRef;
    @ViewChild('img') img: ElementRef;
    private ctx: CanvasRenderingContext2D;
    private element: HTMLImageElement;
    src: string;
    width: number;
    height: number;
    constructor(canvas: ElementRef, img: ElementRef) {
        this.width = window.innerWidth;
        this.height = window.innerHeight;
        this.src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
    }
    ngAfterViewInit() {
        this.ctx = this.canvas.nativeElement.getContext('2d');
        this.element = this.img.nativeElement;
    }
    @HostListener('window:resize')
    resize() {
        this.width = window.innerWidth;
        this.height = window.innerHeight;
        this.render();
    }
    clear() {
        this.ctx.clearRect(0, 0, this.width, this.height);
    }
    render() {
        this.clear();
        this.ctx.drawImage(this.element, 0, 0, 400, 400);
    }
}

所以一切都工作得很好,然而,当我调整窗口大小时,resize回调被击中并调用渲染。然后,画布上的绑定发生了,它重置了上下文,留下了一个空白的画布。我最初的想法是在变更检测发生后再次调用渲染。这是正确的方法还是有更好的方法?

谢谢

@rinukkusu回答正确,谢谢!

也许可以尝试调用渲染方法在ngAfterViewChecked

可接受的答案似乎不是最优解决方案,因为ngAfterViewChecked将被调用多次。另一个解决方案是:

ngAfterViewInit() {
    this.bgImg = new Image();
    this.bgImg.src = this.img;
    const ctx = this.canvasElement.getContext('2d');
    this.bgImg.onload = () => {
        ctx.drawImage(this.bgImg, 0, 0, this.canvasElement.width, this.canvasElement.height);
    }
}