Hidden canvas

by Michał Belka

HTML

<p>To control, click Result part of JS Fiddle and use arrows</p>
<div id="game">
    <canvas id="game-layer" width="300" height="300"></canvas>
    <canvas id="background-layer" width="300" height="300"></canvas>
</div>

CSS

canvas {
    border: 1px red solid;
    position: absolute;
}

#game {
    width: 300px;
    height: 300px;
    position: relative;
}

#game-layer { z-index: 2; }
#background-layer { z-index: 1; }

JavaScript

// First draw grid on background layer
function drawBackground() {
    var ctx = document.getElementById('background-layer').getContext('2d');
    ctx.clearRect(0,0,300,300); // Clear canvas
    for (var x = 0.5; x < 300; x += 10) {ctx.moveTo(x, 0);ctx.lineTo(x, 300);}for (var y = 0.5; y < 300; y += 10) {ctx.moveTo(0, y);ctx.lineTo(300, y);}ctx.strokeStyle = "#ddd";ctx.stroke(); // Grid
}

// Now, the rest is as we know

var move = 0; // 0 - stop, 1 - move
// Direction:
// 0 - left
// 1 - top
// 2 - right
// 3 - down
// 4 - stop
var direction = 4;

var lastX = 10;
var lastY = 10;

function draw() {
    var ctx = document.getElementById('game-layer').getContext('2d');
    ctx.clearRect(0,0,300,300); // Clear canvas
    
    switch (direction) {
        case 0:
            lastX -= 1;
            if (lastX < 0) lost(ctx);
            break;
        case 1:
            lastY -= 1;
            if (lastY < 0)  lost(ctx);
            break;
        case 2:
            lastX += 1;
            if(lastX > 200)  lost(ctx);
            break;
        case 3:
            lastY += 1;
            if (lastY > 200)  lost(ctx);
            break;
        default:
            // no movement
            break;
    }
            
    ctx.fillRect(lastX, lastY, 100, 100);

    if (move == 1) {
        window.requestAnimationFrame(draw);
    }
}

document.addEventListener('DOMContentLoaded', draw, false);
document.addEventListener('DOMContentLoaded', drawBackground, false);

// document.getElementById('control').onkeydown = test;
window.onkeydown = test;

function test(e) {
    switch (e.keyCode) {
        case 37:
            console.log('Left');
            direction = 0;
            break;
        case 38:
            console.log('Top');
            direction = 1;
            break;
        case 39:
            console.log('Right');
            direction = 2;
            break;
        case 40:
            console.log('Down');
            direction = 3;
            break;
       ...