Reputation: 79
Hey guy's I'm making a snake game in JS and right now all I'm trying to do is draw a snake in the center of the canvas. I've set the canvas dimensions to the board dimensions so everything scales right but nothing shows up. Any help would be 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>
Upvotes: 1
Views: 138
Reputation: 50639
This is happening because your snake
is an array of objects. You either need to turn this into a single object for your code to work or use an index to select the object inside.
ctx.fillRect(snake[0].x-unit/2, snake[0].y-unit/2, unit, unit);
Also, note that in order to correctly centre your snake you need to subtract the unit/2
from both x
and y
coordinates.
You can also remove the setting of the canvas dimensions within your code, as this is set when your define the height
and width
attributes on your canvas
element.
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>
Upvotes: 2