block by 1wheel 77c660a764ab55a496c4e37623be9069

canvas-interaction-sorted

Full Screen

With data sorted along the x axis, we can find the closest point even faster.

var [px, py] = d3.mouse(this)
var index = bisect.left(data, px)

var minPoint = null
var minDist = Infinity
var lxDist = 0
var rxDist = 0
var i = 0
while (lxDist < minDist && rxDist < minDist){
  lxDist = checkPoint(data[index - i])
  rxDist = checkPoint(data[index + i])
  i++
}

function checkPoint(d){
  if (!d) return Infinity

  var dx = d.px - px
  var dy = d.py - py
  var dist = Math.sqrt(dx*dx + dy*dy)

  if (dist < minDist){
    minDist = dist
    minPoint = d
  }

  return Math.abs(px - d.px)
}

_script.js

index.html

style.css