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 snakeare 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/2from xand from both y.

You can also remove the setting of the canvas size in your code, as it is set when the heightand widthattribute 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>

Related


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

Can't draw square on canvas using setInterval?

User 10870573 Hey guys, I'm trying to use setInterval to draw a square on the canvas every 70ms. Interval is set to call function draw()this function, which contains the fillRect() method. But I can't get it to work any ideas? Oh, I tried clearRect() but it di

Can't draw square on canvas using setInterval?

User 10870573 Hey guys, I'm trying to use setInterval to draw a square on the canvas every 70ms. Interval is set to call function draw()this function, which contains the fillRect() method. But I can't get it to work any ideas? Oh, I tried clearRect() but it di

Why can't we draw a square like a triangle?

Ramesh Singh I found the code in the android documentation. public class Square { private FloatBuffer vertexBuffer; private ShortBuffer drawListBuffer; // number of coordinates per vertex in this array static final int COORDS_PER_VERTEX = 3; static float squ

Why can't we draw a square like a triangle?

Ramesh Singh I found the code in the android documentation. public class Square { private FloatBuffer vertexBuffer; private ShortBuffer drawListBuffer; // number of coordinates per vertex in this array static final int COORDS_PER_VERTEX = 3; static float squ

Why can't I draw image arrays in HTML5 Canvas?

robert I am trying to draw a tiled map using canvas. There are three types of tiles that need to be drawn to the canvas, so instead of calling the function for each individual image, I pass an array of images as a parameter, then loop through the array and tel

Why can't my card view draw to the canvas?

Robin Dijkhof I am trying to draw cardview to pdf canvas. Unfortunately, the card view is not drawn. However, some test text is drawn. Why isn't my Carview drawing? Code: // start a page PdfDocument.Page page = document.startPage(pageInfo);

Why can't I draw an ellipse with this code?

fast packaging test; Import java.awt. *; Import java.awt.event. *; import java.awt.geom.Ellipse2D; Introduced java.awt.image.BufferedImage; Import javax.swing. *; Public class test_bmp extends MouseListener, MouseMotionListener, ActionListener implemented by

Why can't I draw an ellipse with this code?

fast packaging test; Import java.awt. *; Import java.awt.event. *; import java.awt.geom.Ellipse2D; Introduced java.awt.image.BufferedImage; Import javax.swing. *; Public class test_bmp extends MouseListener, MouseMotionListener, ActionListener implemented by

Why can't I draw elements on stage?

Michael Schwartz Fiddle - http://liveweave.com/JS9EBN This is a starter template for web design applications. (Apart from drawing issues, it's almost always the case) Draw elements to the stage like this. // Handles Drawable Elements $("#canvas").on('mousedown

Why can't I draw textures in pyOpenGL

V_shr If the texture is disabled, the white cube is drawn correctly, but when the texture is enabled, nothing (or a black square of the same color as the background) is drawn. The only thing I suspect is GL_INT, since I've only used unsigned bytes in my projec

Why can't I draw an ellipse with this code?

fast packaging test; Import java.awt. *; Import java.awt.event. *; import java.awt.geom.Ellipse2D; Introduced java.awt.image.BufferedImage; Import javax.swing. *; Public class test_bmp extends MouseListener, MouseMotionListener, ActionListener implemented by

Why can't I draw an ellipse with this code?

fast packaging test; Import java.awt. *; Import java.awt.event. *; import java.awt.geom.Ellipse2D; Introduced java.awt.image.BufferedImage; Import javax.swing. *; Public class test_bmp extends MouseListener, MouseMotionListener, ActionListener implemented by

Why can't I draw an ellipse with this code?

fast packaging test; Import java.awt. *; Import java.awt.event. *; import java.awt.geom.Ellipse2D; Introduced java.awt.image.BufferedImage; Import javax.swing. *; Public class test_bmp extends MouseListener, MouseMotionListener, ActionListener implemented by

Why can't I draw elements on stage?

Michael Schwartz Fiddle - http://liveweave.com/JS9EBN This is a starter template for web design applications. (Apart from drawing issues, it's almost always the case) Draw elements to the stage like this. // Handles Drawable Elements $("#canvas").on('mousedown

Why can't I draw textures in pyOpenGL

V_shr If the texture is disabled, the white cube is drawn correctly, but when the texture is enabled, nothing (or a black square of the same color as the background) is drawn. The only thing I suspect is GL_INT, since I've only used unsigned bytes in my projec

I can't draw rectangle using canvas as child component

Riddle I need to draw a rectangle using canvas. Canvas must be in child component. Just like the updateCanvas function. Is it possible to do so? I am trying to draw a rectangle in the parent component and everything works fine, but in this case I need to put t

I can't draw rectangle using canvas as child component

Riddle I need to draw a rectangle using canvas. Canvas must be in child component. Just like the updateCanvas function. Is it possible to do so? I am trying to draw a rectangle in the parent component and everything works fine, but in this case I need to put t

I can't draw image on Canvas in J2ME

Pawan Jolacia I tried loading the image on Canvas and it worked fine java.io.IOException exception. I don't know in which folder I have to put the images. But now I put the image in F and :\New Folder\DrawImage\src\Waterfall.png.I am using netbean editor for c

I can't draw image on Canvas in J2ME

Pawan Jolacia I tried loading the image on Canvas and it worked fine java.io.IOException exception. I don't know in which folder I have to put the images. But now I put the image in F and :\New Folder\DrawImage\src\Waterfall.png.I am using netbean editor for c

Why can't I set background in canvas

Vladimir Novacek I am trying to put a background image into a canvas like this: import tkinter as tk class App(tk.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.canvas = GameBoard() sel

Can't draw line on canvas

Bill Bulson I'm having trouble drawing lines on an HTML canvas with JavaScript. For the record, I don't want to use any pre-written line drawing methods, I need to do it using pixel manipulation. I try to draw a line on a canvas of 500x500 pixels, for which I

Can't draw squares on canvas

Lords Hi all, I'm starting a snake game with JavaScript. Now, what I'm trying to do is draw a green square in the center of the canvas. I set the fillStyle and used the fillRect method, but I get nothing. Can someone explain the problem, I'd really appreciate

Can't draw on canvas HTML

sky I'm trying to include a canvas element in a form where the user can draw a signature. The border and box are created, but when I try to draw on it, nothing happens. When I put the code that defines the canvas tag outside the form tag, the stroke seems to b

Can't draw squares on canvas

Lords Hi all, I'm starting a snake game with JavaScript. Now, what I'm trying to do is draw a green square in the center of the canvas. I set the fillStyle and used the fillRect method, but I get nothing. Can someone explain the problem, I'd really appreciate

draw a square on the canvas

Sam Hawk I have a canvas that is drawing circles with predefined extents. canvas.drawCircle((float) (getBounds().right / 2), (float) (getBounds().bottom / 2), (float) (getBounds().right / 2), paint); Now I need to make it draw a square instead of a circle. So

draw square image in canvas

Sebastian Corneliu Vîrlan I am trying to display a preview of an uploaded image in a canvas. The preview should be a square version of the image. yes) I have: var img = new Image; img.src = imageSrc; var c = document.getElementById('file-preview-' + data.respo

draw a square on the canvas

Sam Hawk I have a canvas that is drawing circles with predefined extents. canvas.drawCircle((float) (getBounds().right / 2), (float) (getBounds().bottom / 2), (float) (getBounds().right / 2), paint); Now I need to make it draw a square instead of a circle. So

draw square image in canvas

Sebastian Corneliu Vîrlan I am trying to display a preview of an uploaded image in a canvas. The preview should be a square version of the image. yes) I have: var img = new Image; img.src = imageSrc; var c = document.getElementById('file-preview-' + data.respo