Javascript Canvas Game

In this example below you will see how to do a Javascript Canvas Game with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by Nathan, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright Nathan ©
  • HTML
  • CSS
  • JavaScript
    <canvas id="board"></canvas>
<div class="log"><p>Console...</p></div>

/*Downloaded from https://www.codeseek.co/Twinbee/javascript-canvas-game-qpKymy */
    body {
  height: 100vh;
  
  background: #222229;
  margin: 0;
  padding: 0;
  
  position: relative;
  
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

#board {
  height: 320px;
  width: 600px;
  
  background: #000;
  
  box-shadow: 0px 0px 40px #111;
}

.log {
  height: 60px;
  width: 100vw;
  
  padding-left: 40px;
  
  background: black;
  
  font-family: Courier, sans-serif;
  color: lime;
  
  position: fixed;
  bottom: 0;
}


/*Downloaded from https://www.codeseek.co/Twinbee/javascript-canvas-game-qpKymy */
    var canvas = document.getElementById("board");
var ctx = canvas.getContext("2d");
var ballRadius = 5;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;

function drawBall() {
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.fillStyle = "#ffffff";
    ctx.fill();
    ctx.closePath();
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawBall();
    
    if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
        dx = -dx;
    }
    if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
        dy = -dy;
    }
    
    x += dx;
    y += dy;
}

setInterval(draw, 10);

Comments