JSFiddle - React, Tailwind, and code Playground

by sinechris

HTML

<canvas id="gCanvas" width="400" height="400"></canvas>

JavaScript

var config = {
    rows: 25,
    cols: 25,
    width: 10,
    height: 10,
    fps: 30
};

var canvas = document.getElementById("gCanvas");
var ctx = canvas.getContext("2d");

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

function targetBlock(x,y){
    this.x = x;
    this.y = y;
}

function homingBlock(x,y,vx,vy){
    this.x = x;
    this.y = y;
    this.vx = vx;
    this.vy = vy;
}

var targetBlock = new targetBlock(15,15);

function drawCanvas(){
    var colorBit = true;
    ctx.clearRect(0,0,400,400);
    for(var i=0;i<config.rows;i++){
        for(var n=0;n<config.cols;n++){
            var x = n*config.width;
            var y = i*config.height;
            ctx.beginPath();
            ctx.fillStyle = (colorBit) ? "#f1f1f1" : "#ffffff";
            colorBit = !colorBit;
            ctx.fillRect(x,y,config.width, config.height);
        }
    }
    
    // Draw target ball
    ctx.fillStyle="skyblue";
    ctx.fillRect(config.width * targetBlock.x, 
                 config.height * targetBlock.y,
                 config.width,
                 config.height);
    
}

var trailCords = [];

function bindSquareToGridDimensions(square){
    if (square.x >= config.cols - 1 && square.vx > 0) {
        square.vx *= -1;
    }
    if (square.x <= 0 && square.vx < 0) {
        square.vx *= -1;
    }
    if (square.y >= config.rows - 1 && square.vy > 0) {
        square.vy *= -1;
    }
    if (square.y <= 0 && square.vy < 0) {
        square.vy *= -1;
    }
}

var homingBlock = new homingBlock(0,0,1,1);

function drawTrail(){
      
}

function drawHomingBlock(){
    
    homingBlock.x += homingBlock.vx;
    homingBlock.y += homingBlock.vy;
    
    trailCords.push({x:homingBlock.x, y:homingBlock.y});
    console.log(trailCords);
    
    homingBlock.vx = getRandomNumber(-1,1);
    homingBlock.vy = getRandomNumber(-1,1);
    
    bindSquareToGridDimensions(homingBlock);
    
    ctx.fillStyle = "#ff0000";
   ...