javascript - 使 HTML Canvas 适合屏幕

标签 javascript jquery html canvas

我想让 HTML Canvas 元素的宽度 = 浏览器窗口宽度,高度 = 浏览器窗口高度。下面是我使用的代码。

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();
   });

});

无论我做什么,我似乎都无法让 Canvas 适合整个屏幕。我不确定 Canvas 不适合的原因。我认为问题出在 sizeCanvas 函数中。

最佳答案

在你的 CSS 中尝试一下这个:

body {
  margin: 0;
}

#gameCanvas {
  width: 100vw;
  height: 100vh;
}

关于javascript - 使 HTML Canvas 适合屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46443101/

相关文章:

javascript - Ng-click 在第二次点击时触发 Action (不是第一次点击)

javascript - 带有类的事件处理程序

javascript - flask 无法读取静态路径和加载 Javascript 文件

javascript - 同一类 div 的多个倒计时

php - 如何在 jQuery Datepicker 中插入 PHP 值

html - 如何在将鼠标悬停在旁边的链接上时更改自定义图标图像?

angularjs - Google Chrome HTML <select> 元素不选择工作 Google Chrome 移动 View

javascript - 是否可以通过站点树远程或本地直接爬取站点树?

javascript - Google Charts - 避免在 yAxis 中显示负值

javascript - jquery 基于类名的排序不起作用