Uber interview intesecting circles
by kpulkit29
HTML
<canvas id="myCanvas" width="1000" height = "1000"></canvas>
CSS
canvas {
margin-top: 100px;
}
JavaScript
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var radius = 10; // initial radius
let start = 0, end;
const coveredCoordinates = [];
const currColor = "red";
function getRandomColor() {
// generate random R, G, B values
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
// combine R, G, B values into a single color code
const colorCode = `rgb(${r},${g},${b})`;
return colorCode;
}
function getDistance(x1, y1, x2, y2) {
let y = Math.abs(x2 - x1);
let x = Math.abs(y2 - y1);
return Math.sqrt(x * x + y * y);
}
function doesCollide(x1, y1, r1) {
console.log(coveredCoordinates, x1, y1, r1);
for(let item of coveredCoordinates) {
const [x2,y2,r2] = item;
console.log(Math.hypot(Math.abs(x2 - x1), Math.abs(y2 - y1)));
if(Math.hypot(Math.abs(x2 - x1), Math.abs(y2 - y1)) <= r2 + r1) return true;
}
return false;
}
canvas.addEventListener("mousedown", function(event) {
// start drawing when user clicks
start = event.clientX;
end = event.clientY;
/* ctx.beginPath();
ctx.arc(event.clientX, event.clientY, radius, 0, 2 * Math.PI);
ctx.fill(); */
canvas.addEventListener("mousemove", drawCircle);
// continue drawing as user drags
});
canvas.addEventListener("mouseup", function(event) {
// stop drawing when user releases
drawCircle(event);
coveredCoordinates.push([start, end, radius]);
start = undefined;
end = undefined;
canvas.removeEventListener("mousemove", drawCircle);
});
function drawCircle(event) {
ctx.beginPath();
let radius = getDistance(event.clientX, event.clientY, start, end);
ctx.arc(start, end, radius, 0, 2 * Math.PI);
ctx.fillStyle = doesCollide(start, end, radius) ? getRandomColor() : currColor;
ctx.fill();
}