代码之家  ›  专栏  ›  技术社区  ›  piRSquared

如何确保画布包含在视口中

  •  1
  • piRSquared  · 技术社区  · 8 年前

    我有一张画布,这是我唯一想看到的。我试图使它这样,当我调整我的窗口,我总是有整个画布没有滚动条,并保持纵横比可见。

    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 回复  |  直到 8 年前
        1
  •  2
  •   enxaneta    8 年前

    您可能会喜欢阅读本文:[以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>
    推荐文章