Answers for "js game code"

4

how to make a javascript game

//Javascript game template
//Move player with arrow keys

var canvas = document.createElement("canvas");
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");

var player = {x: canvas.width / 2, y: canvas.height / 2, speed: 10};
var keys = [];

function update() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  ctx.beginPath();
  ctx.fillStyle = "red";
  ctx.fillRect(player.x, player.y, 50, 50);
  
  if (keys[37])
    player.x -= player.speed;
  if (keys[38])
    player.y -= player.speed;
  if (keys[39])
    player.x += player.speed;
  if (keys[40])
    player.y += player.speed;
  
  requestAnimationFrame(update);
}
update();

document.onkeydown = function(e) {
  keys[e.keyCode] = true;
}
document.onkeyup = function(e) {
  keys[e.keyCode] = false;
}
Posted by: Guest on May-20-2020
0

javascript game

window.onload = function() {
     canvas = document.createElement("canvas");
     canvas.width = 400;
     canvas.height = 400;
     canvasContext = canvas.getContext("2d");
     document.body.appendChild(canvas);
     setInterval(gameCanvas, 1000/10);
}
function gameCanvas() {
     canvasContext.fillStyle = "black";
     canvasContext.fillRect(0, 0, canvas.width, canvas.height);
     canvasContext.fillStyle = "cyan";
     canvasContext.fillRect(0, 330, 20, 70);
     canvasContext.fillStyle = "orange";
     canvasContext.fillRect(380, 330, 20, 70);
     canvas.addEventListener("click", function() {
          canvasContext.fillStyle = "yellow";
          canvasContext.fillRect(25, 360, 15, 7);
     });
     canvasContext.fillStyle = "darkblue";
     canvasContext.fillRect(0, 0, canvas.width, 100);
     canvasContext.fillStyle = "red";
     canvasContext.fillRect(0, 100, canvas.width, 100);
     canvasContext.fillStyle = "gray";
     canvasContext.fillRect(30, 80, 80, 30);
     canvasContext.fillStyle = "gray";
     canvasContext.fillRect(200, 150, 80, 30);
     canvasContext.fillStyle = "gray";
     canvasContext.fillRect(250, 50, 80, 30);
}
Posted by: Guest on October-08-2021

Browse Popular Code Answers by Language