JSFiddle - React, Tailwind, and code Playground
HTML
<input disabled="true"><button id="nxt">next</button>
<br>
CSS
svg {
position: absolute;
width: 100%;
height: 100%;
}
JavaScript
var svg = d3.select('body')
.append('svg');
svg.append('rect')
.attr('width', '100%')
.attr('height', '100%')
.attr('fill', 'rgba(0,0,0,.2)')
.on('click', handleClick);
svg.append('circle')
.attr('r', '10px')
.attr('cx', '10px')
.attr('cy', '10px')
.attr('fill', 'black');
var points = new Array(100)
, shortestDistance;
var points = d3.range(50).map(function() {
return [
Math.random() * 400 + 35,
Math.random() * 400 + 35
];
});
svg.selectAll('circles')
.data(points)
.enter()
.append('circle')
.attr('fill', 'red')
.attr('r', '10px')
.attr('cx', function (d) { return d[0]; })
.attr('cy', function (d) { return d[1] });
function handleClick(d, i) {
d3.select('input').attr('value', d3.mouse(this));
var coords = d3.mouse(this);
shortestDistance = getDistance(coords[0],coords[1],0,0);
svg.append("path")
.attr("d", function(d) { return line(d) + "Z"; });
svg.append('circle')
.data([coords])
.attr("cx", function (d) { return d[0]; })
.attr("cy", function (d) { return d[1]; })
.attr('r', '10px')
.attr('fill', 'black');
findClosestPoint(coords);
}
function findClosestPoint(coords) {
var dist, coord;
points.forEach(function(point) {
dist = getDistance(coords[0],coords[1],point[0],point[1]);
if(dist < shortestDistance) {
shortestDistance = dist;
coord = point;
}
});
console.log(shortestDistance);
}
function getDistance(x1,y1,x2,y2) {
return Math.sqrt( Math.pow(x1-x2, 2) + Math.pow(y2-y1, 2) );
}