d3.js - 鼠标指针与十字准线指针不同步。在 D3 v6 中
问题描述
使用 D3 v5.16 时。鼠标指针通过使用 . 与我的十字准线指针同步d3.mouse
。它们完全对齐移动。
var coordinates = d3.mouse(this);
将 D3 v5.16 升级到 D3 v6.2时,鼠标指针不再与十字准线指针同步,它们之间存在偏移。我正在使用d3.pointer
代替d3.mouse
来获取鼠标的位置,但这并没有给出确切的坐标。
var coordinates = d3.pointer(event,this);
示例代码
const generator = fc.randomFinancial()
.filter(fc.randomSkipWeekends);
const data = generator(100);
var annoationData = [{ x: data[50].date, y: data[50].high }];
const dateFormat1 = d3.timeFormat("%d/%m/%y");
data.forEach(d => {
d.date = new Date(d.date);
d.high = Number(d.high);
d.close = Number(d.close);
d.open = Number(d.open);
const xExtent = fc.extentDate()
.accessors([d => d.date])
const xScale = fc.scaleDiscontinuous(d3.scaleTime())
.discontinuityProvider(fc.discontinuitySkipWeekends())
.domain(xExtent(data))
.nice()
const yScale = d3
.scaleLinear()
.domain(fc.extentLinear().accessors([d => d.high, d => d.low, d => d.open, d => d.close])(data))
.nice()
const line = fc.seriesSvgLine()
.crossValue(d => d.date)
.mainValue(d => d.high)
const crosshair = fc
.annotationSvgCrosshair()
.x(d => xScale(d.x))
.y(d => yScale(d.y))
.xLabel(d => dateFormat1(d.x))
.yLabel(d => d.y.toLocaleString())
.decorate(selection => {
selection
.enter()
.attr("strokeStyle", "blue")
.style("stroke-dasharray", ("10,1"))
.attr("stroke-width", 1)
selection
.select('.top-handle')
.append('text')
selection.select('.top-handle text').text(d => dateFormat1(d.x));
})
var series = fc
.seriesSvgMulti()
.series([line, crosshair])
.mapping((data, index, series) => {
switch (series[index]) {
case crosshair:
return annoationData;
default:
return data;
}
});
const chart = fc
.chartCartesian(xScale, yScale)
.xLabel('Date')
.yLabel('High')
.xTicks(10)
.xTickFormat(dateFormat1)
.yTickFormat(d3.format("~s"))
.yOrient('right')
.svgPlotArea(series)
.decorate(sel => {
sel.enter()
.select('.plot-area')
.on('mousemove', event => {
var cordinates = d3.pointer(event, this)
var clientX = cordinates[0];
var clientY = cordinates[1];
annoationData[0] = { x: xScale.invert(clientX), y: yScale.invert(clientY) };
render();
})
});
const render = () => {
d3.select('#chart')
.datum(data)
.call(chart)
};
render();
});
解决方案
推荐阅读
- reactjs - 如何使用 jest.mock 模拟 useRef 和反应测试库
- python - 在 plotly-dash 中的 URL 之间共享数据
- google-apps-script - 从谷歌编辑器插件更新文档版本名称
- android - 完成后意图再次开始
- ios - 如何从 [String:[String:String]] 获取值
- javascript - 如何在动态创建的表单中使用 JQuery Ajax 将表单数据提交到 ASP.NET Core MVC 操作
- c# - 如何在现有数据表上创建仅用于更新的默认值的列
- asp.net-core - 使用 Bot 框架在 Microsoft Teams 上发送主动消息
- c# - 为什么ClientName不能在Datatable中显示
- android - 连接到家庭 WiFi 时保持 Android 手机解锁的解决方法