Resize HTML5 canvas to fit window

前端 未结 16 1185
遥遥无期
遥遥无期 2020-11-22 12:03

How can I automatically scale the HTML5 element to fit the page?

For example, I can get a

to scale by setting th
16条回答
  •  太阳男子
    2020-11-22 12:21

    If you're interested in preserving aspect ratios and doing so in pure CSS (given the aspect ratio) you can do something like below. The key is the padding-bottom on the ::content element that sizes the container element. This is sized relative to its parent's width, which is 100% by default. The ratio specified here has to match up with the ratio of the sizes on the canvas element.

    // Javascript
    
    var canvas = document.querySelector('canvas'),
        context = canvas.getContext('2d');
    
    context.fillStyle = '#ff0000';
    context.fillRect(500, 200, 200, 200);
    
    context.fillStyle = '#000000';
    context.font = '30px serif';
    context.fillText('This is some text that should not be distorted, just scaled', 10, 40);
    /*CSS*/
    
    .container {
      position: relative; 
      background-color: green;
    }
    
    .container::after {
      content: ' ';
      display: block;
      padding: 0 0 50%;
    }
    
    .wrapper {
      position: absolute;
      top: 0;
      right: 0;
      left: 0;
      bottom: 0;
    }
    
    canvas {
      width: 100%;
      height: 100%;
    }
    
    
    

提交回复
热议问题