Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an Angular 2 canvas-based component that responds to being resized?

I want to create a component whose view is simply a canvas element. I want this component to:

  • Fill whatever element it is placed with the canvas
  • Determine its width and height during its initialization process
  • Know when it has been resized, figuring out its new height and width, and responding appropriately.

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!

like image 610
MWinstead Avatar asked Oct 28 '16 13:10

MWinstead


People also ask

How do you dynamically resize canvas?

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 .

How do I use canvas in angular 10?

The common approaching to use canvas in javascript is like : var canvas = document. getElementById('tutorial'); var ctx = canvas. getContext('2d');


1 Answers

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>
like image 200
Carlos Mermingas Avatar answered Sep 18 '22 23:09

Carlos Mermingas