我有一些代码在光标位置上方显示一个SVG项目。我注意到物体落在光标后面的距离超过我预期的,如果只是后面的一帧。
var width = 600,
height = 200;
var mouseLocation = [0,0];
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var cursor = svg.append('circle')
.attr("r", 2)
.attr("fill", 'darkblue');
// update mouse location
d3.select(window).on("mousemove", () => {
mouseLocation = d3.mouse(svg.node());
});
// show mouse
d3.timer(function() {
cursor.attr("transform", 'translate(' + mouseLocation + ')');
});

<script src="http://d3js.org/d3.v4.min.js"></script>
&#13;
您可以通过将鼠标从一侧平滑滑动到另一侧来查看延迟。蓝色圆圈略微落后于光标。 (至少在Windows上的Chrome 57上)
我尝试了几种变体,包括在mousemove回调函数中调用circle.attr。但总有一点延迟。
编辑我尝试失败的内容:
mousemove
事件mousemove
调用以来经过的时间,每16 ms仅更新一次。svg.style("shape-rendering", "optimizeSpeed");
mousemove
事件d3.event.pageX
和d3.event.pageY
而不是d3.mouse(svg.node())
<canvas>
demo 答案 0 :(得分:0)
在此答案的第一个版本(查看编辑历史记录)中,我尝试了d3.interval
和setInterval
,但没有区别。
然而,我相信,也许,这个问题没有答案(从OP想要的意义上说),因为滞后取决于处理mousemove
事件的D3。此问题也可能与D3无关,但取决于用户代理(浏览器)如何控制mousemove
事件频率。
如果我们将用于移动圆圈的代码放在非常mousemove
函数中,可以看到这一点:
d3.select(window).on("mousemove", () => {
mouseLocation = d3.mouse(svg.node());
cursor.attr("transform", 'translate(' + mouseLocation + ')');
});
滞后仍然是相同的:
var width = 600,
height = 200;
var mouseLocation = [0,0];
var svg = d3.select("div").append("svg")
.attr("width", width)
.attr("height", height);
var cursor = svg.append('circle')
.attr("r", 2)
.attr("fill", 'darkblue');
// update mouse location
d3.select("div").on("mousemove", () => {
cursor.attr("transform", 'translate(' + (d3.event.pageX - 16) + "," + (d3.event.pageY - 16) + ')');
});
&#13;
<script src="http://d3js.org/d3.v4.min.js"></script>
<div></div>
&#13;