Published
Edited
Sep 10, 2020
2 forks
6 stars
Insert cell
Insert cell
Insert cell
Insert cell
{
const svg = d3.select(DOM.svg(width, height))

var mouseDown = 0;
var wait = 1;
svg
.on("mousedown", function() { mouseDown = 1; })
.on("mouseup", function() { mouseDown = 0; })
.on("mouseleave", function() { mouseDown = 0; })
.on("mousemove", function() {
if (mouseDown && wait) {
wait = 0;
var coordinates= d3.mouse(this);
var mouseX = coordinates[0];
var mouseY = coordinates[1];

svg.append("circle")
.attr("class","drawing")
.attr("fill", "black")
.attr("cx",mouseX)
.attr("cy",mouseY)
.attr("r", 3)

var smallest = 9999;
var index = 0;
check.forEach(function(d,i) {
const distance = Math.sqrt(Math.pow((x(d[0])-mouseX),2) + Math.pow((y(d[1])-mouseY),2))
if (smallest>distance) { smallest = distance; index=i }

})

svg.append("circle")
.attr("class","drawing")
.attr("fill", "grey")
.attr("cx",x(check[index][0]))
.attr("cy",y(check[index][1]))
.attr("r", 3)

svg.append("line")
.attr("class","drawing")
.attr("stroke", "lightgrey")
.attr("x1",x(check[index][0]))
.attr("y1",y(check[index][1]))
.attr("x2",mouseX)
.attr("y2",mouseY)

setTimeout(function(){wait = 1;},20)
}
})


svg
.append("g")
.attr("class", "bottom")
.attr("transform", "translate(0," + (height-margin.bottom) + ")")
.call(d3.axisBottom(x));

svg.append("g")
.attr("class", "left")
.attr("transform", "translate("+ (margin.left) + ",0)")
.call(d3.axisLeft(y));

const line = d3.line()
.x(function(d) { return x(d[0]); })
.y(function(d) { return y(d[1]); })

svg.append("path")
.attr("d",line(pathCoordinates))
.style("fill", "none")
.style("stroke","black")

svg.selectAll("text")
.style("user-select","none")

yield svg.node()
}
Insert cell
Insert cell
pathCoordinates = [[0,10], [20, 50], [20, 50], [40, 50], [50, 70], [60,80], [90,100]]
Insert cell
Insert cell
draw = {
const svg = d3.select(DOM.svg(width, height))
const path = svg.append("path")
.attr("d",d3.line()(pathCoordinates))
yield path.node()
}
Insert cell
Insert cell
l = draw.getTotalLength();
Insert cell
Insert cell
check = d3.range(l+1).map((d,i)=> [draw.getPointAtLength(d).x,draw.getPointAtLength(d).y])
Insert cell
Insert cell
x = d3.scaleLinear()
.domain(d3.extent(pathCoordinates,(d,i)=>d[0]))
.range ([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain(d3.extent(pathCoordinates,(d,i)=>d[1]))
.range ([ height - margin.bottom, margin.top ])
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more