angular2在变化检测后在画布上绘制图像
angular2 drawImage on canvas after change detetion
我有一个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);
}
}
相关文章:
- 画布:逐像素绘制图像并请求动画帧计时
- WebGL绘制图像
- 多重绘制图像后画布清除
- 可以'清除Rect后,不要在画布上绘制图像
- 如何在单页应用程序中重新绘制图像
- 画布中的图像在绘制图像后立即消失
- 使用Canvas绘制图像
- 如何在javascript中在图像上绘制图像(没有CSS和HTML)
- 使用模式在 HTML5/JS 中绘制图像
- 绘制并重新绘制图像以模拟动画是行不通的
- Dart Canvas未绘制图像
- 在新窗口中打开时,未在画布中绘制图像
- 在画布上绘制图像并导出打印质量的图像
- 用一个加载项绘制图像阵列
- html画布绘制图像不起作用
- Chrome 31.0 HTML5画布绘制图像
- 用HTML5和Javascript绘制图像
- 在新框架上绘制图像,同时仍然使用P5.js中的利萨茹曲线
- 如何在画布上更快地绘制图像
- 在 HTML5 画布中绘制图像,同时保留图像