JSFiddle - React, Tailwind, and code Playground

by Gwyn Milcote

HTML

<div id='canvas-container'></div>

CSS

div, canvas, button {
    box-sizing: border-box;
}

#canvas-container {
    padding: 10px;
    box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.5);
}

JavaScript

function randomNumber(min, max){
  return Math.floor(Math.random() * (max - min + 1) + min);
}

function randomArray(array){
    return array[Math.floor(Math.random()*array.length)];
}


class GameRenderer {

   constructor(){
       this.canvas = document.createElement("canvas");
       this.ctx = this.canvas.getContext("2d");
       this.canvas.width = 500;
       this.canvas.height = 400;
       
       // Logic class decides if these
       // updates are needed or not.
       this.updateBoard = true;
       this.updatePieces = true;
       this.updateBonuses = true;
       
       this.render();
   }
   
   /*
   * When cursor moves near edges of canvas,
   * scroll it to reveal more of game board.
   */
   scroll(dir){
         let px = {
             n: [0, -10],
             e: [10, 0],
             s: [0, 10],
             w: [-10, 0],
             nw: [-10, -10],
             ne: [10, -10],
             sw: [-10, 10],
             se: [10, 10]
         };
         px = px[dir];
         let camX = this.camera.x + px[0];
         let camY = this.camera.y + px[1];
         
         // Can camera actually move any further?
         if(camX == this.camera.x && camY == this.camera.y){
             return;
         }
         
         // Clean up. Min/max values.
         if(camX < 10){
              camX = 0;
         }
         if(camY < 10){
              camY = 0;
         }
         if(camX > 790){
              camX = 800;
         }
         if(camY > 790){
              camY = 800;
         }
         
         // Save and re-render.
         this.camera.x = camX;
         this.camera.y = camY;
         this.render();
     }
     
     /*
     * Change zoom settings, + or -.
     */
     zoom(dir){
          if(dir == "in" && this.zoom < 2){
              this.zoom += 0.2;
              this.render();
          }
          if(dir == "out" && this.zoom > 0.4){
              this.zoom -= 0.2;
              this.render();
          }
     }
   
   
  ...