Resize HTML5 canvas to fit window

前端 未结 16 1117
遥遥无期
遥遥无期 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.

提交回复
热议问题