snipplets.dev/projects/JavaScript/Check Dot in Circle/app.js

70 lines
1.5 KiB
JavaScript

let stats = new Stats();
let canvas = null;
let context = null;
let dot = { x: 0, y: 0, size: 2, };
let circle = { x: 0, y: 0, radius: 50, };
window.onload = function() {
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
// add statistics
stats.showPanel(0);
document.body.appendChild(stats.dom);
document.getElementById('canvas').addEventListener('mousemove', (event) => {
let canvas_rect = canvas.getBoundingClientRect();
dot.x = event.clientX - canvas_rect.left;
dot.y = event.clientY - canvas_rect.top;
});
initScene();
requestAnimationFrame(mainLoop);
}
function drawScene() {
'use strict';
clearContext();
// Calculate dot collision and change circle color
if (Math.sqrt((dot.x - circle.x) * (dot.x - circle.x) + (dot.y - circle.y) * (dot.y - circle.y)) <= circle.radius) {
context.fillStyle = '#d44e52';
}
else {
context.fillStyle = '#38607c';
}
// Draw circle
context.beginPath();
context.arc(circle.x, circle.y, circle.radius, 0, 2 * Math.PI);
context.fill();
// Draw dot
context.fillStyle = '#ffcc68';
context.fillRect(dot.x, dot.y, dot.size, dot.size);
}
function initScene() {
circle.x = canvas.width / 2;
circle.y = canvas.height / 2;
}
function mainLoop() {
stats.begin();
drawScene();
stats.end();
requestAnimationFrame(mainLoop);
}
function clearContext() {
'use strict';
context.fillStyle = '#2a2a3a';
context.fillRect(0, 0, canvas.width, canvas.height);
}