Why can't I draw a square on the canvas?
Lords
Hey, I'm making a snake game in JS, and now all I want to do is draw a snake in the center of the canvas. I've set the canvas size to the board size, so everything scales correctly, but nothing shows up. Any help would be greatly appreciated :)
//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>
Nick Parsons
This is because you snake
are an array of objects. You need to turn it into a single object for the code to work properly, or use an index to select objects within it.
ctx.fillRect(snake[0].x-unit/2, snake[0].y-unit/2, unit, unit);
Also, note that in order to properly center the snake, you need to subtract unit/2
from x
and from both y
.
You can also remove the setting of the canvas size in your code, as it is set when the height
and width
attribute is defined on the element canvas
.
See working example below:
//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>