Resize HTML5 canvas to fit window

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

    This worked for me. Pseudocode:

    // screen width and height
    scr = {w:document.documentElement.clientWidth,h:document.documentElement.clientHeight}
    canvas.width = scr.w
    canvas.height = scr.h
    

    Also, like devyn said, you can replace "document.documentElement.client" with "inner" for both the width and height:

    **document.documentElement.client**Width
    **inner**Width
    **document.documentElement.client**Height
    **inner**Height
    

    and it still works.

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

    The following solution worked for me the best. Since I'm relatively new to coding, I like to have visual confirmation that something is working the way I expect it to. I found it at the following site: http://htmlcheats.com/html/resize-the-html5-canvas-dyamically/

    Here's the code:

    <!DOCTYPE html>
    
    <head>
        <meta charset="utf-8">
        <title>Resize HTML5 canvas dynamically | www.htmlcheats.com</title>
        <style>
        html, body {
          width: 100%;
          height: 100%;
          margin: 0px;
          border: 0;
          overflow: hidden; /*  Disable scrollbars */
          display: block;  /* No floating content on sides */
        }
        </style>
    </head>
    
    <body>
        <canvas id='c' style='position:absolute; left:0px; top:0px;'>
        </canvas>
    
        <script>
        (function() {
            var
            // Obtain a reference to the canvas element using its id.
            htmlCanvas = document.getElementById('c'),
            // Obtain a graphics context on the canvas element for drawing.
            context = htmlCanvas.getContext('2d');
    
           // Start listening to resize events and draw canvas.
           initialize();
    
           function initialize() {
               // Register an event listener to call the resizeCanvas() function 
               // each time the window is resized.
               window.addEventListener('resize', resizeCanvas, false);
               // Draw canvas border for the first time.
               resizeCanvas();
            }
    
            // Display custom canvas. In this case it's a blue, 5 pixel 
            // border that resizes along with the browser window.
            function redraw() {
               context.strokeStyle = 'blue';
               context.lineWidth = '5';
               context.strokeRect(0, 0, window.innerWidth, window.innerHeight);
            }
    
            // Runs each time the DOM window resize event fires.
            // Resets the canvas dimensions to match window,
            // then draws the new borders accordingly.
            function resizeCanvas() {
                htmlCanvas.width = window.innerWidth;
                htmlCanvas.height = window.innerHeight;
                redraw();
            }
        })();
    
        </script>
    </body> 
    </html>
    

    The blue border shows you the edge of the resizing canvas, and is always along the edge of the window, visible on all 4 sides, which was NOT the case for some of the other above answers. Hope it helps.

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

    A pure CSS approach adding to solution of @jerseyboy above.
    Works in Firefox (tested in v29), Chrome (tested in v34) and Internet Explorer (tested in v11).

    <!DOCTYPE html>
    <html>
        <head>
        <style>
            html,
            body {
                width: 100%;
                height: 100%;
                margin: 0;
            }
            canvas {
                background-color: #ccc;
                display: block;
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                width: 100%;
                height: 100%;
            }
        </style>
    </head>
    <body>
        <canvas id="canvas" width="500" height="500"></canvas>
        <script>
            var canvas = document.getElementById('canvas');
            if (canvas.getContext) {
                var ctx = canvas.getContext('2d');
                ctx.fillRect(25,25,100,100);
                ctx.clearRect(45,45,60,60);
                ctx.strokeRect(50,50,50,50);
            }
        </script>
    </body>
    </html>
    

    Link to the example: http://temporaer.net/open/so/140502_canvas-fit-to-window.html

    But take care, as @jerseyboy states in his comment:

    Rescaling canvas with CSS is troublesome. At least on Chrome and Safari, mouse/touch event positions will not correspond 1:1 with canvas pixel positions, and you'll have to transform the coordinate systems.

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

    Here's a tiny, complete Code Snippet that combines all the answers. Press: "Run Code Snippet" then press "Full Page" and resize the window to see it in action:

    function refresh(referenceWidth, referenceHeight, drawFunction) {
      const myCanvas = document.getElementById("myCanvas");
      myCanvas.width = myCanvas.clientWidth;
      myCanvas.height = myCanvas.clientHeight;
    
      const ratio = Math.min(
        myCanvas.width / referenceWidth,
        myCanvas.height / referenceHeight
      );
      const ctx = myCanvas.getContext("2d");
      ctx.scale(ratio, ratio);
    
      drawFunction(ctx, ratio);
      window.requestAnimationFrame(() => {
        refresh(referenceWidth, referenceHeight, drawFunction);
      });
    }
    
    //100, 100 is the "reference" size. Choose whatever you want.
    refresh(100, 100, (ctx, ratio) => {
      //Custom drawing code! Draw whatever you want here.
      const referenceLineWidth = 1;
      ctx.lineWidth = referenceLineWidth / ratio;
      ctx.beginPath();
      ctx.strokeStyle = "blue";
      ctx.arc(50, 50, 49, 0, 2 * Math.PI);
      ctx.stroke();
    });
    div {
      width: 90vw;
      height: 90vh;
    }
    
    canvas {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
    <div>
      <canvas id="myCanvas"></canvas>
    </div>

    This snippet uses canvas.clientWidth and canvas.clientHeight rather than window.innerWidth and window.innerHeight to make the snippet run inside a complex layout correctly. However, it works for full window too if you just put it in a div that uses full window. It's more flexible this way.

    The snippet uses the newish window.requestAnimationFrame to repeatedly resize the canvas every frame. If you can't use this, use setTimeout instead. Also, this is inefficient. To make it more efficient, store the clientWidth and clientHeight and only recalculate and redraw when clientWidth and clientHeight change.

    The idea of a "reference" resolution lets you write all of your draw commands using one resolution... and it will automatically adjust to the client size without you having to change the drawing code.

    The snippet is self explanatory, but if you prefer it explained in English: https://medium.com/@doomgoober/resizing-canvas-vector-graphics-without-aliasing-7a1f9e684e4d

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

    CSS

    body { margin: 0; } 
    canvas { display: block; } 
    

    JavaScript

    window.addEventListener("load", function()
    {
        var canvas = document.createElement('canvas'); document.body.appendChild(canvas);
        var context = canvas.getContext('2d');
    
        function draw()
        {
            context.clearRect(0, 0, canvas.width, canvas.height);
            context.beginPath();
            context.moveTo(0, 0); context.lineTo(canvas.width, canvas.height); 
            context.moveTo(canvas.width, 0); context.lineTo(0, canvas.height); 
            context.stroke();
        }
        function resize()
        {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
            draw();
        }
        window.addEventListener("resize", resize);
        resize();
    });
    
    0 讨论(0)
  • 2020-11-22 12:19

    Using jQuery you can track the window resize and change the width of your canvas using jQuery as well.

    Something like that

    $( window ).resize(function() {
     		$("#myCanvas").width($( window ).width())
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">

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