From 66bfe0351b102c597839c0f2ae8cea0f9ff6dc80 Mon Sep 17 00:00:00 2001 From: SondreB Date: Sat, 16 Nov 2024 23:51:19 +0100 Subject: [PATCH] Add resize of canvas --- .../photo-collage/photo-collage.component.ts | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/app/photo-collage/photo-collage.component.ts b/src/app/photo-collage/photo-collage.component.ts index 0b45b2c..2193766 100644 --- a/src/app/photo-collage/photo-collage.component.ts +++ b/src/app/photo-collage/photo-collage.component.ts @@ -1,4 +1,4 @@ -import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core'; +import { Component, ElementRef, ViewChild, AfterViewInit, OnDestroy } from '@angular/core'; import { CommonModule } from '@angular/common'; interface PhotoElement { @@ -25,7 +25,7 @@ interface HoveredPhoto extends PhotoElement { templateUrl: './photo-collage.component.html', styleUrls: ['./photo-collage.component.css'] }) -export class PhotoCollageComponent implements AfterViewInit { +export class PhotoCollageComponent implements AfterViewInit, OnDestroy { @ViewChild('canvas') canvasRef!: ElementRef; @ViewChild('fileInput') fileInput!: ElementRef; @@ -53,16 +53,31 @@ export class PhotoCollageComponent implements AfterViewInit { controlsPosition = { x: 0, y: 0 }; private isOnControls = false; + private resizeHandler = () => { + this.setupCanvas(); + }; + ngAfterViewInit() { this.canvas = this.canvasRef.nativeElement; this.ctx = this.canvas.getContext('2d')!; this.setupCanvas(); this.setupEventListeners(); + window.addEventListener('resize', this.resizeHandler); + } + + ngOnDestroy() { + window.removeEventListener('resize', this.resizeHandler); } private setupCanvas() { - this.canvas.width = window.innerWidth; - this.canvas.height = window.innerHeight; + const parent = this.canvas.parentElement; + if (parent) { + this.canvas.width = parent.clientWidth; + this.canvas.height = parent.clientHeight; + } else { + this.canvas.width = window.innerWidth; + this.canvas.height = window.innerHeight; + } this.render(); }