
本文旨在解决在使用 `lightweight-charts` 图表库时,如何通过监听十字光标移动事件,准确获取十字光标首次和最后一次移动时的 X 坐标值的问题。文章将详细介绍一种实现方案,该方案通过结合 `addEventListener` 和 `subscribeCrosshairMove()` 函数,并利用状态变量来跟踪十字光标的移动状态,从而实现对起始和结束坐标的精确捕获。
在使用 lightweight-charts 时,经常需要获取十字光标移动时的坐标数据,例如,获取十字光标在图表上移动的起始位置和结束位置。 直接在 subscribeCrosshairMove() 事件中简单地赋值,可能会因为事件的持续触发而导致无法准确获取到所需的值。
原始代码尝试在 try 块内使用 let initialX 声明变量,导致每次事件触发时 initialX 都会被重新定义,因此 else 语句永远不会执行。同时,在十字光标移动结束之前,无法直接获取到最后一个 X 值,因为 subscribeCrosshairMove() 事件仍在持续触发。
为了解决上述问题,我们需要将状态变量定义在事件监听器外部,并且需要一种机制来判断十字光标移动的开始和结束。 以下是一种可行的解决方案:
let coordinates = {
shiftKey: false,
fromX: null,
toX : null
}
let fromX = null;
let toX = null;
// Register the shiftKey pressing & releasing.
document.addEventListener('mousemove', function( e ){
if( e.shiftKey && !coordinates.shiftKey ) {
coordinates.shiftKey = true;
}
if( !e.shiftKey && coordinates.shiftKey ) {
coordinates.shiftKey = false;
}
})
async function crossHairEvent(param){
try{
// Register the fromX
if( coordinates.shiftKey && !coordinates.fromX ) {
coordinates.fromX = param.time;
}
// Register the toX
if( !coordinates.shiftKey && !coordinates.toX ) {
coordinates.toX = param.time;
}
// Save the values in a deifferent variables.
if( coordinates.fromX && coordinates.toX ) {
fromX = coordinates.fromX;
toX = coordinates.toX ;
// Set them to null to make it possible to register every time you release the shiftKey.
coordinates.fromX = null;
coordinates.toX = null;
}
}
catch{}
};
chart.subscribeCrosshairMove(crossHairEvent);代码解释:
通过结合 addEventListener 和 subscribeCrosshairMove() 函数,并利用状态变量来跟踪十字光标的移动状态,我们可以准确地获取十字光标首次和最后一次移动时的 X 坐标值。 这种方法可以应用于各种需要精确获取十字光标坐标数据的场景。
以上就是获取轻量图表中十字光标移动的起始和结束坐标数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号