[英]why can't I draw a square on the canvas?
嗨,我正在用JS做蛇游戲,現在我要做的就是在畫布中央畫一條蛇。 我已經將畫布尺寸設置為木板尺寸,因此一切都可以正確縮放,但是什么都沒有顯示。 任何幫助,將不勝感激:)
//declare global variables const canvas = document.querySelector('#canvas'); //set canvas context const ctx = canvas.getContext('2d'); //set canvas dimensions to board dimensions canvas.width = 768; canvas.height = 512; //put canvas dimensions into variables const cvsW = canvas.width; const cvsH = canvas.height; //create snake unit const unit = 16; //create snake and set starting position let snake = [{ x : cvsW/2, y : cvsH/2 }] ctx.fillStyle = 'limegreen'; ctx.fillRect(snake.x, snake.y, unit, unit);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Snake</title> <style> body { background-color: #333; } #canvas { background-color: #4d4d4d; display: block; margin: auto; position: absolute; left: 0; top: 0; right: 0; bottom: 0; } </style> </head> <body> <canvas id="canvas" width="768" height="512"></canvas> <script src="script.js"></script> </body> </html>
發生這種情況是因為您的snake
是一組對象。 您需要將其變成單個對象以使代碼正常工作,或者使用索引在其中選擇對象。
ctx.fillRect(snake[0].x-unit/2, snake[0].y-unit/2, unit, unit);
另外,請注意,為了正確地使蛇居中,您需要從x
和y
坐標中減去unit/2
。
您還可以在代碼內刪除畫布尺寸的設置,因為這是在canvas
元素上定義height
和width
屬性時設置的。
請參見下面的工作示例:
//declare global variables const canvas = document.querySelector('#canvas'); //set canvas context const ctx = canvas.getContext('2d'); //put canvas dimensions into variables const cvsW = canvas.width; const cvsH = canvas.height; //create snake unit const unit = 16; //create snake and set starting position let snake = [{ x: cvsW / 2, y: cvsH / 2 }]; ctx.fillStyle = 'lime'; ctx.fillRect(snake[0].x - unit / 2, snake[0].y - unit / 2, unit, unit);
body { background-color: #333; } #canvas { background-color: #4d4d4d; display: block; margin: auto; position: absolute; left: 0; top: 0; right: 0; bottom: 0; }
<canvas id="canvas" width="768" height="512"></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.