如何确保视口中包含画布

时间:2018-10-04 16:23:14

标签: javascript css html5 canvas

我有一个画布,这是我真正想要看到的页面上唯一的东西。我试图做到这样,当我调整窗口大小时,我总是可以看到整个画布,没有滚动条并保持宽高比。

MCVE

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

let w = canvas.width;
let h = canvas.height;

ctx.fillStyle = 'teal';
ctx.fillRect(0, 0, w, h);

ctx.strokeStyle = 'red';
ctx.lineWidth = 10;
ctx.rect(5, 5, w - 5, h - 5);
ctx.stroke();
* {
  background-color: white;
  max-height: 100%;
  max-width: 100%;
  margin: 0;
  padding: 0;
}

div#canvasDiv {}

canvas#canvas {
  display: block;
  margin: auto;
}
<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
  </head>

  <body>
    <div id="canvasDiv">
      <canvas id="canvas" width="500" height="500" />
    </div>
  </body>

</html>

All here at jsfiddle

通过这种尝试,当我调整宽度大小时,它可以重新缩放。但是,当我调整高度时,会溢出。

使用适当的缩放比例调整宽度

enter image description here

调整高度,避免不必要的溢出

enter image description here

1 个答案:

答案 0 :(得分:2)

您可能想读这篇文章:[以CSS为中心:完整指南](https://css-tricks.com/centering-css-complete-guide/

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

let w = canvas.width;
let h = canvas.height;

ctx.fillStyle = 'teal';
ctx.fillRect(0, 0, w, h);

ctx.strokeStyle = 'red';
ctx.lineWidth = 10;
ctx.rect(5, 5, w - 5, h - 5);
ctx.stroke();
* {
  background-color: white;
  max-height: 100%;
  max-width: 100%;
  margin: 0;
  padding: 0;
}


canvas#canvas {
  display: block;
  margin: auto;
  position:absolute;
  top:0;bottom:0;
  left:0;
  right:0;
  
}
   <div id="canvasDiv">
      <canvas id="canvas" width="500" height="500"/>
    </div>