Nimrod Naim Nimrod Naim - 7 months ago 27
Javascript Question

cant move two canvas rectangles at same time

I asked another question today and i have another one..

but first here is the code:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<script type="text/javascript">
var x = 100;
var y = 100;
var xmoveFirst = 720;
var ymoveFirst = 0;
var xmoveSecond = 30 ;
var ymoveSecond = 0;
function canvas() {
var can = document.getElementById('theCanvas'); = "black";
var ctx = can.getContext('2d');

//first player

//second player
ctx.fillStyle = 'white';

//first player move
function move(event) {
ctx.clearRect(0,0,750,750); //clear rects
if (event.keyCode == 40) {

else if (event.keyCode == 38) {

else if (event.keyCode == 83) {
ymoveSecond +=25;

else if (event.keyCode==87) {
ymoveSecond -=25;

var movement = document.addEventListener("keydown", move);


<body onload="canvas()">
<canvas id="theCanvas" width="750" height="750"></canvas>

so each one of the rect is moving perfectly :)
but here is the problem..
I cant move them both togheter..

thanks for helping!!


The problem is, that the browser can only handle 1 pressed key at a time. To bypass this, you need to following things:

  • An array
  • Two event listeners, one for the keydown and one for the keyup event.

The array will hold the currently pressed keys. In the keydown event listener you need to set the element at the same index as the id of the pressed key to true, and in the keyup eventlistener you need to set the same element to false. Example:

var keys = [];

document.addEventListener("keydown", function(e) {
    keys[e.keyCode] = true;

document.addEventListener("keyup", function(e) {
    keys[e.keyCode] = false;

This will make sure, that an element stays true until the key is released. You can check, if a key is currently pressed by checking the element with the same index:

if (keys[87]) {
    // The "W" key is pressed
if (keys[83]) {
    // The "S" key is pressed
/// ...

Note: You shouldn't use else-ifs when you check for the pressed keys.