JSFiddle - React, Tailwind, and code Playground
by AniHouse
HTML
<canvas id="canvas" width="300" height="300"></canvas>
CSS
canvas{ border: 1px solid black; }
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
function checkCollision() {
//square bounding box
if (impactSquare.x < square.x + square.width &&
impactSquare.x + impactSquare.width > square.x &&
impactSquare.y < square.y + square.height &&
impactSquare.height + impactSquare.y > square.y) {
// collision detected!
//square.graphics.beginFill("#F4F4F4");
console.log("Collision Detected");
} else {
// no collision
//square.graphics.beginFill("#FF0000");
console.log("No Collision");
}
}
var impactSquare = {x:150, y:150, width:50, height:50};
var square = {x:50, y:150, width:50, height:50};
setInterval(function(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = "black";
checkCollision();
square.x++;
ctx.fillRect(square.x, square.y, square.width, square.height);
ctx.fillStyle = "blue";
ctx.fillRect(impactSquare.x, impactSquare.y, impactSquare.width,impactSquare.height);
},30);