Skip to content

Instantly share code, notes, and snippets.

@AlexisPister
Last active December 8, 2019 10:51
Show Gist options
  • Save AlexisPister/c60d570d6739a28dfd8ba0c9eae76866 to your computer and use it in GitHub Desktop.
Save AlexisPister/c60d570d6739a28dfd8ba0c9eae76866 to your computer and use it in GitHub Desktop.
scatter drag
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
let width = 960,
height = 500,
radius = 3,
transform = d3.zoomIdentity
let canvas = d3.select("body").append("canvas")
.attr("width", width)
.attr("height", height)
let ctx = canvas.node().getContext("2d");
let data = d3.range(200)
.map(() => { return {"x": d3.randomNormal()(),
"y": d3.randomNormal()()}})
let scaleX = d3.scaleLinear()
.domain(d3.extent(data, function(d){return d.x}))
.range([0, width])
let scaleY = d3.scaleLinear()
.domain(d3.extent(data, function(d){return d.y}))
.range([height, 0])
//canvas.call(d3.zoom()
// .on("zoom", zoomed))
canvas.call(d3.drag()
.subject(dragSubject)
.on("drag", dragged))
function zoomed(){
transform = d3.event.transform
render()
}
function dragSubject(){
x = d3.event.x
y = d3.event.y
for(let i = 0; i < data.length; i++){
console.log("loop")
point = data[i]
dx = x - scaleX(point.x)
dy = y - scaleY(point.y)
if (dx * dx + dy * dy < radius * radius){
/*
console.log("print")
console.log(d3.event.x)
console.log(d3.event.y)
console.log(point)
console.log(scaleX(point.x))
console.log(scaleY(point.y)) */
return data[i];
}
}
}
function dragged(){
console.log("PRINT")
console.log(d3.event.subject.x)
console.log(scaleX.invert(d3.event.x))
console.log(d3.event.x)
d3.event.subject.x = scaleX.invert(d3.event.x)
d3.event.subject.y = scaleY.invert(d3.event.y)
render()
}
function render(){
ctx.save()
ctx.clearRect(0, 0, width, height)
ctx.beginPath()
//ctx.translate(transform.x, transform.y)
//ctx.scale(transform.k, transform.k)
data.forEach(function(d){
ctx.moveTo(scaleX(d.x) + radius, scaleY(d.y))
ctx.arc(scaleX(d.x), scaleY(d.y), radius, 0, Math.PI * 2)
})
ctx.stroke()
/*
ctx.globalAlpha = 0.2
ctx.fillStyle = "blue"
ctx.fillRect(0,0,width,height) */
ctx.restore()
}
render()
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment