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 didn't work.

//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
}]

//create a variable to store the direction of the snake
let direction;

//add event to read users input then change direction
document.addEventListener('keydown', (e) => {
	if(e.keycode == 37 && direction != 'right') direction = 'left';
	else if (e.keycode == 38 && direction != 'down') direction = 'up';
	else if (e.keycode == 39 && direction != 'left') direction = 'right';
	else if (e.keycode == 38 && direction != 'up') direction = 'down';
})

//move snake in chosen direction
if(direction == 'left') snake[0].x -= unit;
else if(direction == 'right') snake[0].x += unit;
else if(direction == 'up') snake[0].y -= unit;
else if(direction == 'down') snake[0].y += unit;

function draw() {
	ctx.fillStyle = 'limegreen';
	ctx.fillRect(snake[0].x - unit/2, snake[0].y - unit/2, unit, unit);
}


setInterval(70, draw);
<!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>

Vito SRG

There are some errors in your code, but I think this is what you mean:

<!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>
        //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
        }]

        //create a variable to store the direction of the snake
        let direction;

        //add event to read users input then change direction
        document.addEventListener('keydown', (e) => {
            if (e.keyCode == 37 && direction != 'right') direction = 'left';
            else if (e.keyCode == 38 && direction != 'down') direction = 'up';
            else if (e.keyCode == 39 && direction != 'left') direction = 'right';
            else if (e.keyCode == 40 && direction != 'up') direction = 'down';

            //move snake in chosen direction
            if (direction == 'left') snake[0].x -= unit;
            else if (direction == 'right') snake[0].x += unit;
            else if (direction == 'up') snake[0].y -= unit;
            else if (direction == 'down') snake[0].y += unit;

            console.log(e.keyCode, direction);
        })

        function draw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = 'limegreen';
            ctx.fillRect(snake[0].x - unit/2, snake[0].y - unit/2, unit, unit);
            console.log('oi');
        }


        setInterval(draw, 70);
    </script>
</body>
</html>

caution:

  1. parameter order ofsetInterval
  2. case sensitiveevent.keyCode

Related


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 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

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

Dynamically draw and draw Square using HTML canvas

Inder Singh I need to draw the chart given below using html canvas. Can anyone help me. http://1.bp.blogspot.com/-em2abcEg5nU/Ts_c3cNtfMI/AAAAAAAAABU/eQWc6SJtD0M/s1600/t31.jpg loo First access the canvas: var can=document.getElementById('canvas1') Now you nee

Dynamically draw and draw Square using HTML canvas

Inder Singh I need to draw the chart given below using html canvas. Can anyone help me. http://1.bp.blogspot.com/-em2abcEg5nU/Ts_c3cNtfMI/AAAAAAAAABU/eQWc6SJtD0M/s1600/t31.jpg loo First access the canvas: var can=document.getElementById('canvas1') Now you nee

Can't draw proper circle using canvas

Xiajin In any case, I can't get a proper circle to draw. I am always oval. Here is sample code to show you what I mean: function canvasClicked(number) { var c = "canvas" + number; var canvas = document.getElementById(c); var context = canvas.getContext("

How to draw a perfect square using tkinter canvas?

sajib ali I want to create a square on mouse drag. I can only create rectangles with canvas.create_rectangle(oldX,oldY , newX , newY,fill = 'red',outline = "") Is there any way to just create squares? acw1668 You can use the maximum or minimum width and heig

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

Can't draw multiple shapes on canvas when using clearRect

eim64 When I use ctx.clearRect before all objects are drawn, only the last object is drawn (with newer chrome and firefox). Everything is drawn without clearRect. //in interval for(var i = 0;i<objects.length;i++){ ctx.clearRect(0, 0, canvas.width, canv

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

Can't draw lines to HTML5 canvas using JavaScript

User 4471744 I am using the following code to draw a line on an html canvas. But unfortunately I can't see any lines on the canvas. I didn't even find any errors. <!DOCTYPE html> <html> <head> <title>TODO supply a title</title> <meta charse

Can't draw lines to HTML5 canvas using JavaScript

User 4471744 I am using the following code to draw a line on an html canvas. But unfortunately I can't see any lines on the canvas. I didn't even find any errors. <!DOCTYPE html> <html> <head> <title>TODO supply a title</title> <meta charse

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

Android Canvas drawLine can't draw on MainActivity

Broadwell I want to draw a line on Main Activity using Canvas. The problem is, it doesn't draw anything. I have the following code: Bitmap bitmap = Bitmap.createBitmap(1920, 1080, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); Paint paint = ne

Canvas draw text - can't get string

Italy String str = new String(); str = "111"; x = width / 2; y = Math.round(height / 1.3); while (pressed != true){ if (!holder.getSurface().isValid()) continue; Canvas c = holder.lockCanvas(); c.drawBitmap(galaxy, 0, 0, null); c.draw

Can't draw on canvas with custom view

Mirko I have a class like the GameActivityfollowing (I only posted the relevant parts): public class GameActivity extends AppCompatActivity { // initiate variables private GameView mGameView; private Display mDisplay; private Point mSize; public static int w

Can't draw to canvas in Tkinter after() loop

discrete tomatoes I'm having a problem, when I try to create an image on the canvas, I can't generate the image. However, I can create and configure my image before starting the after() loop. Also, I am able to use my canvas to delete objects canvas.delete()in

Can't draw on html5 canvas

who I am I created a Hi dpi canvas and then tried to draw the box, but something went wrong. Why can't I paint on canvas, can someone help me? No error occurs, the plot function is executing, but I have no results var HiDPICanvas = function(container_id, color

Can't draw editText in Android canvas

User 3858843 I am trying to add editText box to my android project. This project is almost entirely done in Java (almost no XML), so I would like to know how to do this in Java. The implementation I'm currently encountering the runtime error with is the follow

Can't draw editText in Android canvas

User 3858843 I am trying to add editText box to my android project. This project is almost entirely done in Java (almost no XML), so I would like to know how to do this in Java. The implementation I'm currently encountering the runtime error with is the follow

Can't draw on html5 canvas

who I am I created a Hi dpi canvas and then tried to draw the box, but something went wrong. Why can't I paint on canvas, can someone help me? No error occurs, the plot function is executing, but I have no results var HiDPICanvas = function(container_id, color

Android Canvas drawLine can't draw on MainActivity

Broadwell I want to draw a line on Main Activity using Canvas. The problem is, it doesn't draw anything. I have the following code: Bitmap bitmap = Bitmap.createBitmap(1920, 1080, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); Paint paint = ne