简体   繁体   English

如何使 canvas 按比例响应?

[英]How to make a canvas proportionally responsive?

I am currently working on a pong game with angular for the frontend, the game is drawn inside an html canvas.我目前正在使用 angular 作为前端的乒乓球游戏,该游戏是在 html canvas 内绘制的。

here is the html code:这是 html 代码:

<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.当我在宽度上减小 window 时,canvas 会得到相应的响应,但在高度上却不一样。 See photos below:见下面的照片:

Before reducing the window:在减少 window 之前: 在此处输入图像描述 After reducing the width of the window:减小 window 的宽度后: 在此处输入图像描述 After reducing the height of the window:降低 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?正如您所看到的,当我降低高度时它与宽度不同,有没有办法让我的 canvas 的高度与宽度一样响应?

EDIT编辑

When I use vmin instead of % for the css width of the canvas it fixes the problem but another one came.当我对 canvas 的 css 宽度使用 vmin 而不是 % 时,它解决了问题,但又出现了另一个问题。 See photos below:见下面的照片:

When I totally reduce the window:当我完全减少 window 时: 在此处输入图像描述 When I totally reduce the window only on the width:当我仅在宽度上完全减小 window 时: 在此处输入图像描述

var document= document.getElementById("canvas-container"); var document=document.getElementById("canvas-container");

var width = window.innerWidth ||变量宽度 = window.innerWidth || document.clientWidth;文档.clientWidth;

var height = window.innerHeight ||变量高度 = window.innerHeight || document.clientHeight文档.clientHeight

You always can use fromEvent rxjs operator您始终可以使用 fromEvent rxjs 运算符

  //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 stackblitzstackblitz

After many tests I found out that the best solution my issue was to use vmin unit for the css of my canvas on the width and the height respecting the aspect ratio(55% of the width is the height)经过多次测试后,我发现最好的解决方案是我的 canvas 的 css 在宽高比方面使用 vmin 单位(宽度的 55% 是高度)

<canvas #gameCanvas id="canvas-container" width="950" height="525" style="width: 100vmin;height: 55vmin;"></canvas>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM