2016-05-13 87 views
0

我是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; 
} 
+0

也许你的''有一些填充?你有这个代码给我们测试吗? – Arg0n

回答

0

如果您已经设置了你的CSS正确有帆布搭了整个物理屏幕(内屏),然后下面的工作。

基本上不使用窗口的宽度和高度,大小画布的CSS和正确使用画布clientWidth和高度

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

    } 
}); 

P.S.下次更好地格式化你的代码

相关问题