Dual canvas

by Luis Martin

HTML

<canvas style="border:1px solid #d3d3d3;" id="g" width="200" height="200"></canvas>
<canvas style="border:1px solid #d3d3d3;" id="g2" width="200" height="200"></canvas>

<img hidden id="f1" width="10" height="10" src="https://i.stack.imgur.com/LwVIw.png
">
<img hidden id="s" width="10" height="10" src="http://home.skku.edu/~mspl/bbs/images/admin1_face.gif" alt="The Scream">

CSS

canvas {
  position: absolute;
  top: 10;
  left: 10;
}

JavaScript

var canvas1 = document.getElementById("g");
var canvas2 = document.getElementById("g2");

var ctx1 = canvas1.getContext("2d");
var ctx2 = canvas2.getContext("2d");

v = 2;

svx = 0;
svy = 0;

ctx1.drawImage(document.getElementById("f1"), 0, 0);

  sx = sy = (canvas1.width / 2) - 5;

setInterval(update, 1000 / 30);

document.onkeydown = checkKeys;
document.onkeyup = dontMove;

function update() {

  //points += pointPerSecond / 30;
  ctx2.clearRect(0, 0, canvas1.width, canvas1.height);


  //ctx2.fillRect(sx, sy, 10, 10);
  sx += svx;
  sy += svy;

  ctx2.drawImage(document.getElementById("s"), sx, sy);
}

function checkKeys(e) {
  e = e || window.event;
  if (e.keyCode == '38' || e.keyCode == '87') {
    // up arrow
    console.log("up");
    svy = -v;
    svx = 0;
  } else if (e.keyCode == '40' || e.keyCode == '83') {
    // down arrow
    console.log("down");
    svy = v;
    svx = 0;
  } else
  if (e.keyCode == '37' || e.keyCode == '65') {
    // left arrow
    console.log("left");
    svy = 0;
    svx = -v;
  } else if (e.keyCode == '39' || e.keyCode == '68') {
    // right arrow
    console.log("right");
    svy = 0;
    svx = v;
  } else if (e.keyCode == "32") {
    // space bar
    console.log("shot");
    //isPaused = true;
  }
}

function dontMove() {
  svx = 0;
  svy = 0;
}