我想创建一个视图只是canvas元素的组件。我想要这个组件:
我想我可以通过将组件模板中画布的宽度和高度指定为100%来实现第一部分,如下所示:
@Component({
selector: 'canvas-component',
template:'<canvas style="width:100%; height:100%"></canvas>'
})
但我不知道如何处理第二或第三部分。
最终目标是能够在画布中绘制占据画布相同大小的形状,无论其大小如何。例如,我想绘制一个直径为画布宽度3/4的圆圈 - 所以如果画布增大或缩小,圆圈也应该重新绘制,增长或缩小。 / p>
我不知道这是否重要,但我在打字稿中制作网络应用程序。
有谁知道实现这一目标的好方法?我正在寻找最多的&#34; Angular方式&#34;可能,因为这是我用来学习Angular 2的个人项目。
提前致谢!
答案 0 :(得分:4)
这远非“回答”,但应该让你前进:
<强>组件强>
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;
}
}
<强>模板强>
<div (window:resize)="onResize()"></div>
<canvas #myCanvas style="width:100%; height:100%" width="150" height="150"></canvas>
答案 1 :(得分:0)
另一种方法:在模板中引入父容器并绑定其尺寸。
在canvas-panel.component.html
中<div #canvasWrapper class="canvas-wrapper" (window:resize)="draw()">
<canvas id="wfcanvas" #canvasId
[height]="canvasWrapper.offsetHeight"
[width]="canvasWrapper.offsetWidth">
</canvas>
</div>
在canvas-panel.component.css中
.canvas-wrapper {
width: 94%;
height: 128px;
margin: auto;
}
在canvas-panel.component.ts
import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-canvas-panel',
templateUrl: './canvas-panel.component.html',
styleUrls: ['./canvas-panel.component.scss']
})
export class CanvasPanelComponent implements OnInit {
@ViewChild('canvasId') canvasRef: ElementRef;
constructor() {
}
ngOnInit() {
}
draw() {
let ctx: CanvasRenderingContext2D =
this.canvasRef.nativeElement.getContext('2d');
console.log("canvas size: ", ctx.canvas.width, ctx.canvas.height);
}
}
答案 2 :(得分:-1)
使用画布调整大小功能 在component.html中:
<canvas #mycanvas class="canvasc" id="canvas"></canvas>
在component.ts中:
// Somewhere above your class constructor
@ViewChild('mycanvas') mycanvas: any;
public context: CanvasRenderingContext2D;
public ctx: CanvasRenderingContext2D;
ngAfterViewInit(): void {
this.ctx = this.mycanvas.nativeElement.getContext('2d');
this.mycanvas.nativeElement.onresize = this.Function;
}