I am currently working on a small Web App Game written angular. I wanted to add a feature for users to draw their on profile picture using a canvas HTML element.
I never worked with canvas before so i searched the internet for examples and i found this one which really helped me out getting started. So i created a component and used exactly this code which worked immediately. My next goal was to make the canvas size responsive, so it looks good on every device. A quick google search gave me multiple ways to achive this:
width: 100%; height: 100%
to the canvas stylengAfterViewInit()
like this: canvasEl.style.width = "100%";
canvasEl.style.height = "100%";
canvasEl.width = canvasEl.offsetWidth;
canvasEl.height = canvasEl.offsetHeight;
Both solution kind of worked. The canvas was now as big as possible which was great. However the drawing did not work properly anymore. When drawing the canvas wasn't changing at all or the lines were not created at the position of the cursor (instead of increased canvas size it felt like the canvas was stretched and the actual size in pixel did not change).
As CBroe mentioned i have to set the width and height of the properties of the canvas itself.
So now i am trying to retrieve the height and width of the parent container in ngAfterViewInit()
but the values are always zero:
@ViewChild('parent') parent: ElementRef;
ngAfterViewInit() {
...
console.log (this.parent.nativeElement.offsetHeight);
...
}
html code:
<div #parent fxFlex>
<canvas id="responsive-canvas" #myCanvas></canvas>
</div>
After a lot of try and error i found a solution to my problem which looks like that:
replaced the height and width set in the ngAfterViewInit()
of the canvas with this code
canvasEl.style.width = "100%";
canvasEl.style.height = "100%";
canvasEl.width = canvasEl.offsetWidth;
canvasEl.height = canvasEl.offsetHeight;
and this is what my html code looks like:
<div #parent fxFlex style="height: 200px;">
<canvas
id="responsive-canvas"
[height]="parent.offsetHeight"
[width]="parent.offsetWidth"
#myCanvas
>
</canvas>
</div>
It is important, that the height of the parent is set. Otherwise it does not work.