使HTML Canvas适合屏幕 [英] Make HTML Canvas fit screen

查看:28
本文介绍了使HTML Canvas适合屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做,以使HTML Canvas元素的width =浏览器窗口的宽度,而height =浏览器窗口的高度.下面是我使用的代码.

I would like to make it so that the HTML Canvas element has a width = to the browser window width, and height = the browser window height. Below is the code I use.

HTML:

   <body>
       <canvas id="gameCanvas"></canvas>
   <body />

JS:

function Main() {
   this.canvas;
   this.context;
   this.canvasWidth;
   this.canvasheight;

   this.screenWidth;
   this.screenHeight;

   this.boxWidth;
   this.boxHeight;

   //This function is used to gather all required startup data
   this.initalize = function (canvas) {
      this.canvas = canvas;
      this.context = this.canvas[0].getContext('2d');

   }

   //This function is used to size the canvas to the screen size
   this.sizeCanvas = function () {
      this.canvas.css("width", this.screenWidth + "px");
      this.canvas.css("height", this.screenHeight + "px");
      this.canvas[0].width = this.screenWidth;
      this.canvas[0].height = this.screenHeight;


   }

   //This function is used to draw a stickman
   this.drawStickMan = function (x, y) {
      var headRadius = 0;
      if (this.boxWidth < this.boxHeight) {
          headRadius = this.boxWidth;

      } else {
          headRadius = this.boxHeight;

      }

      this.context.beginPath();
      this.context.arc(x + this.boxWidth, y + this.boxHeight, headRadius, 0, 2 * Math.PI);
      this.context.stroke();
      console.log("run" + this.boxHeight);

   }

   //This function is run on page load, and when the screen resizes
   this.resize = function () {
      this.screenWidth = screen.width;
      this.screenHeight = screen.height;
      this.sizeCanvas();

      this.canvasWidth = this.canvas[0].width;
      this.canvasheight = this.canvas[0].height;

      this.boxWidth = this.canvasWidth / 16;
      this.boxHeight = this.canvasheight / 32;
      this.drawStickMan(100, 100);

   }

}

运行上述类的JS:

   //This function is used to run the game
$(document).ready(function () {
   var main = new Main();
   main.initalize($("#gameCanvas"));
   main.resize();

   //run whenever screen size changes
   $(window).resize(function () {
      main.resize();
   });

});

无论我做什么,似乎都无法使画布适合整个屏幕.我不确定画布不适合的原因.我相信问题出在 sizeCanvas 函数中.

No matter what I do I cannot seem to get the canvas to fit the entire screen. I am unsure of the reason the canvas will not fit. I believe that the problem is in the sizeCanvas function.

推荐答案

尝试一下:

html, body {
    height: 100%;
}

#gameCanvas {
    width: 100%;
    height: 100%;
}

100%必须从html元素中过滤掉,否则它将无法填满屏幕的高度.

The 100% has to filter down from the html element or else it won't fill the height of the screen.

这篇关于使HTML Canvas适合屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆