JSFiddle - React, Tailwind, and code Playground

by scotp71

HTML

<canvas width="400" height="400" id="myCanvas"></canvas>
<br/>

JavaScript

var timer = window.setInterval(callAnimation, 50);
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

window.requestAnimFrame = (function (callback) {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
        window.setTimeout(callback, 1000 / 60);
    };
})();


var currentMousePos = { x: -1, y: -1 };
$(document).mousemove(function(event) {
  currentMousePos.x = event.pageX;
  currentMousePos.y = event.pageY;
});

function callAnimation() {
    requestAnimFrame(function () {
        animate(rectangles, canvas, context);
    });
}

var rectangles = new Array();
var firstRectangle = {
	x: currentMousePos.x,
  y: currentMousePos.y,
  width: 20,
  height: 20,
  borderWidth: 1,
  borderColor: 'black',
  fillColor: 'orange'
}
rectangles[0] = firstRectangle;
for (var i = 1; i<5; i++){
	rectangles[i] = {
  x: (currentMousePos.x+20), 
  y: (currentMousePos.y+20),
  width: 20,
  height: 20,
  borderWidth: 1,
  borderColor: 'black',
  fillColor: 'blue'
  }
}

function drawRectangle(r, c) {
    c.beginPath();
    c.rect(r.x, r.y, r.width, r.height);
    c.fillStyle = r.fillColor;
    c.fill();
    c.lineWidth = r.borderWidth;
    c.strokeStyle = r.borderColor;
    c.stroke();
}

function animate(r, can, con)
{
    if (r[0].x < 100 || r[0].x > 300) step *= -1;
    r[0].x += step;
    r[1].y += step;     
    con.clearRect(0, 0, can.width, can.height);
    
    var rc0 = r[0].fillColor;
    var rc1 = r[1].fillColor;
    
    if (collision(r[0], r[1]))
    {
        r[0].fillColor = 'red';
        r[1].fillColor = 'red';
    }
    
    drawRectangle(r[0], con);
    drawRectangle(r[1], con);
    
    r[0].fillColor = rc0;
    r[1].fillColor = rc1;
}