[英]Flickering translation with d3 v4 drag function
完整的代码在observablehq上是可见和可修改的
相关部分:
const columns = svg.selectAll("g")
.data(nested_city)
.enter()
.append("g")
.attr("city", function(d) { return d.key ;})
.attr("x", function(d) { return x(d.key) ;})
.attr("y", "0")
.attr("transform", function(d) { return "translate(" + x(d.key) + ",0)" ;})
.attr("class", "column")
.on("mouseover", function(d) {
d3.select(this)
.style("cursor","pointer");
})
.on("mouseout", function(d){
d3.select(this)
.style("cursor","default");
})
.call(d3.drag()
.subject(function() {
var t = d3.select(this);
var tr = getTranslation(t.attr("transform"));
return {x: t.attr("x") + tr[0],
y: t.attr("y") + tr[1]};
})
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
和拖动处理程序:
function dragstarted(d) {
d3.select(this).raise().classed("active", true);
}
function dragged(d) {
d3.select(this).attr("transform", function(d,i){
var coordinates = d3.mouse(this);
var mx = coordinates[0]
console.log( coordinates[0])
return "translate(" + [mx,0] + ")"})
}
function dragended(d) {
d3.select(this).classed("active", false);
}
我正在尝试将 d3 v4 版本的新拖放与翻译( 在 SO 上找到)适应我在 observableHQ 上的示例,但没有成功。
当我拖动两列中的任何一列(在旧 x 值和新 x 值跳转之间交替)时,我有一个非常奇怪的闪烁行为。
如果你知道为什么?
在dragged()
函数中有一个d3.mouse(this)
语句。 这将返回当前事件相对于指定容器 ( ref ) 的 x 和 y 坐标。 您的mouse(<container>)
就是this
,表示拖动的<g>
元素。 但它应该是<svg>
。 因此,您应该改用d3.mouse(svg.node())
。
但要小心,因为您没有考虑到<g>
内的偏移量(很难描述)。 也许您必须在<g>
中添加光标位置的坐标。
恕我直言,无论如何我宁愿使用d3.event
而不是d3.mouse
示例。
编辑:具有正确坐标的新拖动功能
// New: Coordinates inside <g>
var coordG = 0;
function dragstarted(d) {
// New: Read out coordinates inside <g>
coordG = d3.mouse(this)[0];
d3.select(this).raise().classed("active", true);
}
function dragged(d) {
d3.select(this).attr("transform", function(d,i){
var coordinates = d3.mouse(svg.node());
var mx = coordinates[0] - coordG;
console.log( coordG);
return "translate(" + [mx,0] + ")";
});
}
function dragended(d) {
d3.select(this).classed("active", false);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.