JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id='myCanvas' height="400" width="600"></canvas>
<div id='pos'>Pos:x,y</div>
<div id='number'>00</div>
<input type='button' id='btn' value='Clear' OnClick="clearB()" class='button' />
JavaScript
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
Balls = [];
colors = ['#000000', '#FD0006'];
canvas.addEventListener("mousemove", click, false);
function click(event) {
var i;
document.getElementById('pos').innerHTML = 'x:' + event.pageX + ' y:' + event.pageY;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < Balls.length; i++) {
ctx.fillStyle = "red";
difx = Balls[i].x - event.pageX;
dify = Balls[i].y - event.pageY;
dist = Math.sqrt(difx * difx + dify * dify);
if (dist < Balls[i].r) {
document.getElementById('number').innerHTML = 'n:' + i;
Balls[i].c = colors[1];
Balls[i].draw();
} else {
Balls[i].c = colors[0];
Balls[i].draw();
}
}
}
/* declarando estrutura */
Ball = function () {
this.x = 0;
this.y = 0;
this.r = 0;
};
Ball.pt = Ball.prototype;
/* func para iniciar valores */
Ball.pt.init = function (px, py) {
this.x = px;
this.y = py;
this.r = 20;
this.c = colors[0];
}
Ball.pt.draw = function () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fillStyle = this.c;
ctx.fill();
}
function create(color) {
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 30; j++) {
b = new Ball();
b.init(20 + j * 40, 20 + i * 40);
b.draw();
Balls.push(b);
}
}
}
function clearB() {
for (var i = 0; i < Balls.length; i++)
Balls.pop();
create();
}
create();