I am currently working on a pong game with angular for the frontend, the game is drawn inside an html canvas.
here is the html code:
<div style="height: 70%; width: 70%;" align="center">
<canvas id="canvas-container" width="950" height="525" style="width: 100%;"></canvas>
</div>
The canvas get proportionally responsive when I reduce the window on the width but it doesn't work the same on the height. See photos below:
Before reducing the window: After reducing the width of the window: After reducing the height of the window:
As you can see when I reduce the height it doesn't work the same as the width, is there a way to make the height of my canvas as responsive as the width ?
EDIT
When I use vmin instead of % for the css width of the canvas it fixes the problem but another one came. See photos below:
When I totally reduce the window: When I totally reduce the window only on the width:
CodePudding user response:
var document= document.getElementById("canvas-container");
var width = window.innerWidth || document.clientWidth;
var height = window.innerHeight || document.clientHeight
CodePudding user response:
You always can use fromEvent rxjs operator
//declare an observable
height$ = fromEvent(window, 'resize').pipe(
startWith(null),
map((_) => {
const factor = 525 / 925; //relation original: height/width
const width = window.innerWidth - 50;
const height = window.innerHeight - 50;
if (height > width * factor)
return { height: width * factor, width: width };
return { height: height, width: height / factor };
})
);
And use like
<div *ngIf="{ dim: height$ | async } as dim">
<canvas
#myCanvas
style="background-color:yellow"
[height]="dim.dim.height"
[width]="dim.dim.width"
></canvas>
</div>
See stackblitz