Resize HTML5 canvas to fit window

前端 未结 16 1119
遥遥无期
遥遥无期 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:30

    I believe I have found an elegant solution to this:

    JavaScript

    /* important! for alignment, you should make things
     * relative to the canvas' current width/height.
     */
    function draw() {
      var ctx = (a canvas context);
      ctx.canvas.width  = window.innerWidth;
      ctx.canvas.height = window.innerHeight;
      //...drawing code...
    }
    

    CSS

    html, body {
      width:  100%;
      height: 100%;
      margin: 0;
    }
    

    Hasn't had any large negative performance impact for me, so far.

    0 讨论(0)
  • 2020-11-22 12:31

    I'm using sketch.js so after I run the init command for the canvas i change the width and height with jquery. It bases the dimensions on the parent element.

    $('#DrawCanvas').sketch().attr('height',$('#DrawCanvas').parent().height()).attr('width',$('#DrawCanvas').parent().width());

    0 讨论(0)
  • 2020-11-22 12:33
    function resize() {
    
        var canvas = document.getElementById('game');
        var canvasRatio = canvas.height / canvas.width;
        var windowRatio = window.innerHeight / window.innerWidth;
        var width;
        var height;
    
        if (windowRatio < canvasRatio) {
            height = window.innerHeight;
            width = height / canvasRatio;
        } else {
            width = window.innerWidth;
            height = width * canvasRatio;
        }
    
        canvas.style.width = width + 'px';
        canvas.style.height = height + 'px';
    };
    
    window.addEventListener('resize', resize, false);
    
    0 讨论(0)
  • 2020-11-22 12:34

    If your div completely filled the webpage then you can fill up that div and so have a canvas that fills up the div.

    You may find this interesting, as you may need to use a css to use percentage, but, it depends on which browser you are using, and how much it is in agreement with the spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element

    The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.

    You may need to get the offsetWidth and height of the div, or get the window height/width and set that as the pixel value.

    0 讨论(0)
提交回复
热议问题