如何创建响应调整大小的Angular 2基于画布的组件?

MWi*_*ead 5 html5-canvas angular

我想创建一个视图只是一个canvas元素的组件.我希望这个组件:

  • 用画布填充放置的任何元素
  • 在初始化过程中确定其宽度和高度
  • 知道何时调整大小,确定其新的高度和宽度,并做出适当的响应.

我想我可以通过将组件模板中画布的宽度和高度指定为100%来实现第一部分,如下所示:

@Component({
selector: 'canvas-component',
template:'<canvas style="width:100%; height:100%"></canvas>'
})
Run Code Online (Sandbox Code Playgroud)

但我不知道如何进行第二或第三部分.

最终目标是能够在画布中绘制占据画布相同大小的形状,无论其大小如何.举个例子,我想绘制一个直径为画布宽度3/4的圆圈 - 所以如果画布增大或缩小,圆圈也应该重新绘制,增长或缩小.

我不知道这是否重要,但我正在使用Typescript制作网络应用程序.

有谁知道实现这个目标的好方法?我正在寻找最可能的"Angular方式",因为这是我用来学习Angular 2的个人项目.

提前致谢!

Car*_*gas 5

这远不是一个“答案”,但应该可以帮助您:

零件

import { Component, ViewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('myCanvas') canvas;

  onResize() {
    // Not a good thing to do but will get you going.
    // I need to look into the Renderer service instead.
    const canvasElement = this.canvas.nativeElement;

    // These don't change (canvas intrinsic dimensions)
    const canvasWidth = canvasElement.width;
    const canvasHeight = canvasElement.height;

    // These will change (scaling applied by the style)
    const computedStyles = getComputedStyle(canvasElement);
    const computedWidth = computedStyles.width;
    const computedHeight = computedStyles.height;
  }
}
Run Code Online (Sandbox Code Playgroud)

模板

<div (window:resize)="onResize()"></div>
<canvas #myCanvas style="width:100%; height:100%" width="150" height="150"></canvas>
Run Code Online (Sandbox Code Playgroud)