【问题标题】:Can't Refer to Window Width/Height in Canvas无法在画布中引用窗口宽度/高度
【发布时间】:2016-05-13 11:35:06
【问题描述】:

我是 html/css/js 的新手,正在尝试学习画布。我想制作一个与窗口大小相同的画布,无论窗口大小如何,然后我想在该窗口中绘制一个额外的矩形,在该矩形上开始绘制迷宫游戏。我可以使用窗口调整画布大小,但只能通过设置主体的溢出:隐藏(当我没有设置时,高度总是太大)。我想知道这是否是现在导致问题的原因。当我尝试在主画布矩形内创建一个较小的矩形时,我将矩形宽度设置为窗口大小的一半,但它远离屏幕。我究竟做错了什么?我只是希望矩形清楚地位于主画布的周边范围内,这样我就可以看到所有边缘。

JS:

$(document).ready(function() {

var ctx;
var ww;
var wh;

drawcanvas();

$(window).resize(function() {
ctx.clearRect(0, 0, ww, wh);  //won't this clear only the bottom     rectangle?
drawcanvas();
});



function drawcanvas() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ww = window.innerWidth;
wh = window.innerHeight;

ctx.canvaswidth = ww;
ctx.canvas.height = wh;
ctx.fillStyle ="blue";
ctx.fillRect(0, 0, ww, wh);

ctx.strokeStyle = 'orange';
ctx.strokeRect(10, 20, ww/2, wh/2);

}



});

HTML:

<html>
<head>
<link href="maze2.css" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js" type="text/javascript" ></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>


<script src="maze2.js" type="text/javascript"></script>
<title>Maze</title>
</head>




<body>


<canvas id="canvas">Your browser does not support Canvas.</canvas>



</body>
</html>

CSS:

body {
width: 100%;
height: 100%;
margin:0px;
overflow:hidden;
}

#canvas {
width:100%;
height:100%;
margin:0px;
}

【问题讨论】:

  • 也许你的&lt;body&gt; 有一些填充?你有这个代码供我们测试吗?

标签: javascript html css canvas window


【解决方案1】:

如果您已正确设置您的 css 以使画布占据整个物理屏幕(内屏幕),那么以下内容将起作用。

基本上不使用窗口宽度和高度,使用 css 正确调整画布大小并使用画布客户端宽度和高度

$(document).ready(function() {
   var canvas = document.getElementById('canvas');
   var ctx = canvas.getContext('2d');
   var cW;
   var cH;
   size();
   drawcanvas();

   $(window).resize(function() {
       size();
       drawcanvas();
   });

   function size(){
      cW = canvas.clientWidth; // if you did your css correctly this will work
      cH = canvas.clientHeight;
      canvas.width = cW, // if the size has changed the canvas will be blanked out automatically
      canvas.height = cH;
   }

   function drawcanvas() {
     ctx.fillStyle ="blue";
     ctx.fillRect(0, 0, cW, cH);

     ctx.strokeStyle = 'orange';
     ctx.strokeRect(10, 20, cW/2, cH/2);

   }
});

附:下次更好地格式化你的代码

【讨论】:

    猜你喜欢
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多