2016-05-13 85 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.下次更好地格式化你的代碼

相關問題