Published unlisted
Edited
Oct 13, 2021
Insert cell
Insert cell
Insert cell
d3 = require('d3@6')
Insert cell
{
const width = 950;
const height = 500;
var svg = d3.create("svg").attr('width', width).attr('height',height);
const originX = width / 2;
const originY = height / 2;

const xScale = d3.scaleLinear().domain([-width/2, width/2]).range([0,width]);
const yScale = d3.scaleLinear().domain([-height/2, height/2]).range([height,0]);
console.log(xScale(100));
svg.selectAll("circle")
.data([{x: 100, y: 200, xPos: 100, yPos: 200}])
.enter().append("circle")
//.attr("cx", d => xScale(d.xPos))
//.attr("cy", d => yScale(d.yPos))
.attr("cx", d => xScale(d.x))
.attr("cy", d => yScale(d.y))
.attr("r", 100)
.call(d3.drag()
//Subject sets the origin in SVG canvas of the drag -- all event.x,event.y updates are then relative
//to this position. If we don't set the subject, then initially event.x and event.y are the position
//of the circle in data space, but updates to event.x and event.y occur in pixel space
// .subject(function(event, d) { return {x: event.x, y: event.y}; }) // Clicking edge of circle jumps circle center to click pt.
.subject(function(event, d) { return {x: xScale(d.x), y: yScale(d.y)}; }) // Clicking on edge of circle does does not jump circle.
.on("drag", dragged));

console.log(svg.node());

function dragged(event, d) {
// console.log("d.yPos: ", d.yPos);
console.log("d.y: ", d.y);
console.log("event.y: ", event.y);
// console.log("event.dy: ", event.dy);
// console.log("yScale.invert(event.y): ", yScale.invert(event.y));
//Update the data values attached to the circle based on the current event.x by converting
//the event.x and event.y back into data space. If we comment these two lines out drag is fine
//but the circle will jump to the initial position d.x=0, d.y=0 when a new drag is started.
// d.xPos = xScale.invert(event.x);
// d.yPos = yScale.invert(event.y);
d.x = xScale.invert(event.x);
d.y = yScale.invert(event.y);
d3.select(this).attr("cx", event.x).attr("cy", event.y);
}
return svg.node()
}

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