JSFiddle - React, Tailwind, and code Playground
JavaScript
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 400;
document.body.appendChild(canvas);
function draw(rect, color) {
if(rect) {
context.fillStyle = color;
context.fillRect(rect.x, rect.y, rect.w, rect.h);
}
};
var r1 = { x:100, y: 100, w:50, h: 100 };
var r2 = { x:140, y: 140, w:50, h: 100 };
function CGRectUnion(rect1, rect2) {
var rightEdge1 = rect1.x+rect1.w;
var rightEdge2 = rect2.x+rect2.w;
var bottomEdge1 = rect1.y+rect1.h;
var bottomEdge2 = rect2.y+rect2.h;
if(rect1.x > rightEdge2 || rightEdge1 < rect2.x || rect1.y > bottomEdge2 || bottomEdge1 < rect2.y) {
return false;
}
return {
x: Math.max(rect1.x, rect2.x),
y: Math.max(rect1.y, rect2.y),
w: Math.min(rightEdge1, rightEdge2) - Math.max(rect1.x, rect2.x),
h: Math.min(bottomEdge1, bottomEdge2) - Math.max(rect1.y, rect2.y)
};
}
var mouse = { x:0, y:0 };
canvas.addEventListener("mousemove", function(e) {
mouse.x = e.pageX;
mouse.y = e.pageY;
});
function animate() {
requestAnimationFrame(animate);
canvas.width = 400;
canvas.height = 400;
r2.x = mouse.x;
r2.y = mouse.y;
draw(r1, "#ffff00");
draw(r2, "#ff00ff");
draw(CGRectUnion(r1, r2), "#ff0000");
};
animate();