如何使用JS获取nipple.js双摇杆的中心点及摇杆位置属性
解决nipple.js摇杆位置与尺寸属性获取问题
nipple.js创建的实例自带DOM元素引用,结合原生JS API就能轻松拿到你需要的位置、尺寸及中心点信息,具体方法如下:
1. 获取摇杆区域(Zone)的基础属性
你传入的mstick、astick就是摇杆的容器区域,直接用getBoundingClientRect()获取其尺寸与中心点:
// 获取mstick区域的视口坐标、尺寸及中心点 const mstickZoneRect = mstick.getBoundingClientRect(); const mstickZoneCenter = { x: mstickZoneRect.left + mstickZoneRect.width / 2, y: mstickZoneRect.top + mstickZoneRect.height / 2 }; // astick区域同理 const astickZoneRect = astick.getBoundingClientRect(); const astickZoneCenter = { x: astickZoneRect.left + astickZoneRect.width / 2, y: astickZoneRect.top + astickZoneRect.height / 2 };
2. 获取可拖动摇杆(Nipple)的实时位置
方式一:通过事件监听获取交互时的实时状态
nipple.js会在摇杆移动时触发move事件,回调参数里直接包含摇杆的位置、半径等关键数据:
// 监听mstick摇杆移动 window.mstick.on('move', (evt, data) => { // data.position:摇杆相对于Zone左上角的相对坐标 // data.radius:摇杆的半径 const nippleRelativePos = data.position; // 转换为视口绝对坐标 const nippleAbsolutePos = { x: mstickZoneRect.left + nippleRelativePos.x, y: mstickZoneRect.top + nippleRelativePos.y }; // 摇杆中心点(相对坐标加半径,或绝对坐标加半径) const nippleCenter = { x: nippleAbsolutePos.x + data.radius, y: nippleAbsolutePos.y + data.radius }; console.log('mstick摇杆实时位置:', nippleAbsolutePos); console.log('mstick摇杆中心点:', nippleCenter); }); // astick摇杆同理 window.astick.on('move', (evt, data) => { const nippleRelativePos = data.position; const nippleAbsolutePos = { x: astickZoneRect.left + nippleRelativePos.x, y: astickZoneRect.top + nippleRelativePos.y }; const nippleCenter = { x: nippleAbsolutePos.x + data.radius, y: nippleAbsolutePos.y + data.radius }; console.log('astick摇杆实时位置:', nippleAbsolutePos); console.log('astick摇杆中心点:', nippleCenter); });
方式二:主动获取当前摇杆的静态状态
如果不需要实时监听,可直接从实例中取出摇杆的DOM元素,再用原生API获取属性:
// 获取mstick当前摇杆的DOM元素 const mstickNippleEl = window.mstick.get(0).el; const mstickNippleRect = mstickNippleEl.getBoundingClientRect(); // 摇杆中心点 const mstickNippleCenter = { x: mstickNippleRect.left + mstickNippleRect.width / 2, y: mstickNippleRect.top + mstickNippleRect.height / 2 }; // astick摇杆同理 const astickNippleEl = window.astick.get(0).el; const astickNippleRect = astickNippleEl.getBoundingClientRect(); const astickNippleCenter = { x: astickNippleRect.left + astickNippleRect.width / 2, y: astickNippleRect.top + astickNippleRect.height / 2 };
关键提示
- 初始化后未拖动摇杆时,摇杆默认处于Zone中心,此时
data.position的x、y值为(Zone宽度/2 - 摇杆半径)、(Zone高度/2 - 摇杆半径)。 getBoundingClientRect()返回的是视口相对坐标,若需文档相对坐标,需加上window.scrollX和window.scrollY。
内容的提问来源于stack exchange,提问作者Darkside
相关产品推荐
相关产品推荐

