[英]Drag position in d3
const width = grid.clientWidth;
const height = grid.clientHeight;
svg.attr("width", width).attr("height", height);
const xValue = d => d.cx;
const yValue = d => d.cy;
const xScale = scaleLinear()
.domain([-10, 10])
.range([0 , width])
.nice();
const yScale = scaleLinear()
.domain([-10, 10])
.range([height , 0 ])
.nice();
svg
.append("g")
.attr("transform", `translate(${0},${yScale(0)})`)
.call(axisBottom(xScale));
svg
.append("g")
.attr("transform", `translate(${xScale(0)},${0})`)
.call(axisLeft(yScale));
function dragged(d) {
console.log(event.x);
select(this)
.attr("cx", (d.x = event.x))
.attr("cy", (d.y = event.y))
.attr("transform", d => `translate(${xScale(xValue(d))},${yScale(yValue(d))})`);
}
const pointG = svg.append("g");
pointG
.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", d => xValue(d))
.attr("cy", d => yValue(d))
.attr("transform", `translate(${d => xScale(xValue(d))},${d => yScale(yValue(d))})`)
.attr("r", radius).call(
drag()
.on("drag", dragged)
);;
};
const data = [
{
cx: 9.0,
cy: -9.38
}
{
cx: 5.0,
cy: 9.0
}
];
基本上我想实现一个像 Desmos 坐标平面这样的工具: https ://www.desmos.com/calculator/q8mwzeylbk。
我已经在 svg 的中心绘制了一个坐标平面,现在我在这个坐标平面上绘制了一些点。 问题是拖动后我会得到像素坐标而不是我想要的坐标。 如何根据坐标平面获取拖动点的坐标? 我应该使用 scale.invert() 函数来转换 SVG 坐标吗?
您已经设置了比例函数,要获取x
和y
,请在dragged()
函数中使用它:
var planeX = xScale(xValue(d));
var planeY = yScale(yValue(d));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.