gpt4 book ai didi

javascript - d3 - 获取标签的 x 和 y 的比例

转载 作者:行者123 更新时间:2023-11-30 16:36:10 25 4
gpt4 key购买 nike

我创建了一个像这样的 x 和 y 比例尺:

var xScale = d3.scale.linear()
.domain([0, 20])
.range([0, width]);

var yScale = d3.scale.linear()
.domain([0, 20])
.range([height, 0]);

然后我使用它来创建 x 和 y 轴以及如何相对于这些轴定位线:

var line = {
start: {x: 2, y: 3, type: 'start'},
finish: {x: 14, y: 6, type: 'finish'}
};

var g = svg.append('g');

g.append('line')
.style('stroke', 'blue')
.attr('class', 'line')
.attr('x1', xScale(line.start.x))
.attr('y1', yScale(line.start.y))
.attr('x2', xScale(line.finish.x))
.attr('y2', yScale(line.finish.y));

我还放置了标示线的 x 轴和 y 轴位置的标签。线的端点是可拖动的,但我无法在拖动事件中获得缩放坐标:

var drag = d3.behavior
.drag()
.on("drag", function(d) {
var circle = d3.select(this),
line = d3.select('.line'),
isStart = circle.classed('start'),
textClass = isStart ? ".textstart" : ".textfinish",
lineX = isStart ? 'x1' : 'x2',
lineY = isStart ? 'y1' : 'y2',
text = d3.select(textClass);

text.text( function (d) { return "( " + d.x + ", " + d.y +" )"; });

line.attr(lineX, d3.event.x).attr(lineY, d3.event.y);
text.attr('x', d3.event.x).attr('y', d3.event.y - 20);
circle.attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
});

这是一个jsbin这说明了问题。

最佳答案

我可以建议你换行吗:

text.text( function (d) { return "( " + d.x  + ", " + d.y +" )"; });

到:

text.text( function (d) { return "( " + d3.format(",.2f")(xScale.invert(d.x))  + ", " + d3.format(",.2f")(yScale.invert(d.y)) +" )"; });

这样您将显示您想要的值,如下图所示:

enter image description here

发生这种情况的原因是因为您传递给函数的对象 d 是 d3.behaviour,它具有 x 和 y,即您拖动到的鼠标位置。因此,您需要使用 invert 将 x,y 鼠标坐标分别转换为它们对应的 xScale 和 yScale 的 x,y 值。

不幸的是,在您的对象 中,您有 x 和 y,这一定导致了混淆。

希望对您有所帮助。

关于javascript - d3 - 获取标签的 x 和 y 的比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32671754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com