JSFiddle - React, Tailwind, and code Playground
by twobomb three
HTML
<canvas id = "canvas" width = "320" height = "320"></canvas>
JavaScript
document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var x = 0,y = 0,hx = 0,hy = 0;
n = [];
n.push({x:0,y:0});
n.push({x:100,y:100});
n.push({x:80,y:20});
document.addEventListener("mousemove",function(e){
x = e.pageX;
y = e.pageY;
});
(function game(){
ctx.clearRect(0,0,320,320);
var minDist = null;
for(i in n){
ctx.fillStyle = "black";
ctx.fillRect(n[i].x,n[i].y,10,10);
if(minDist == null || minDist > getDist(n[i].x,n[i].y,x,y)){
hx = n[i].x;
hy = n[i].y;
minDist = getDist(n[i].x,n[i].y,x,y);
}
}
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.moveTo(x,y);
ctx.lineTo(hx,hy);
ctx.stroke();
ctx.closePath();
requestAnimationFrame(arguments.callee)
})()
///Получить растояние между двумя точками
function getDist(x, y, x1, y1) {
return Math.hypot(x - x1, y - y1);
}