I want to create a component whose view is simply a canvas element. I want this component to:
I figure I can achieve the first part by specifying the width and height of the canvas in my component's template as 100%, like this:
@Component({
selector: 'canvas-component',
template:'<canvas style="width:100%; height:100%"></canvas>'
})
But I have no idea how to go about the second or third parts.
The ultimate goal is to be able to draw shapes in the canvas that take up the same relative size of the canvas, regardless of its size. As an example, I'd want to draw a circle with a diameter of 3/4 the width of the canvas - so if the canvas grows or shrinks, the circle should be re-drawn, growing or shrinking as well.
I don't know if it matters, but I'm making the web app in Typescript.
Does anyone know of a good way of achieving this? I'm looking for doing it the most "Angular way" possible, since this is a personal project I'm using to learn Angular 2.
Thanks in advance!
Resizing the canvas on the fly is quite easy. To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas .
The common approaching to use canvas in javascript is like : var canvas = document. getElementById('tutorial'); var ctx = canvas. getContext('2d');
This is far from an "answer" but should get you going:
Component
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;
}
}
Template
<div (window:resize)="onResize()"></div>
<canvas #myCanvas style="width:100%; height:100%" width="150" height="150"></canvas>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With