All examples By author By category About

1wheel

canvas-interaction-sorted

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)
}