WinWheel库分段索引从1开始导致数据库加载分段异常求助
WinWheel分段索引问题解决方案
问题描述
WinWheel库的分段(Segments)采用1起始索引设计,导致从数据库加载6个分段数据后,创建的theWheel对象中segments数组出现7个元素,第一个为null,其余6个才是正确数据。数据库存储的分段数据格式如下:
[ { "image": "./assets/img/5.png", "strokeStyle": "black", "size": 60, "text": "5% korting" }, { "image": "./assets/img/4.png", "strokeStyle": "black", "size": 60, "text": "10% korting" }, { "image": "./assets/img/5.png", "strokeStyle": "black", "size": 60, "text": "5% korting" }, { "image": "./assets/img/4.png", "strokeStyle": "black", "size": 60, "text": "10% korting" }, { "image": "./assets/img/5.png", "strokeStyle": "black", "size": 60, "text": "5% korting" }, { "image": "./assets/img/4.png", "strokeStyle": "black", "size": 60, "text": "15% korting" } ]
使用fetch获取数据并创建WinWheel实例后,控制台打印的原始数据正常,但theWheel的segments数组异常,尝试forEach循环处理无效,需要解决分段加载错误的问题。
解决方案
1. 适配WinWheel的1索引机制(推荐)
WinWheel内部默认segments数组索引从1开始,会自动在索引0位置填充null。你可以主动构造符合要求的数组,在原始分段数据前添加一个占位元素:
// 调整分段数组,添加索引0的占位 const adjustedSegments = [null, ...data.segments];
然后在WinWheel配置中使用adjustedSegments替代data.segments:
theWheel = new Winwheel({ // ... 其他配置项 'segments': adjustedSegments, // ... 动画、pins等配置 });
这样theWheel的segments数组索引1-6对应你的6个分段,索引0的null是库预期的占位,不会影响转盘渲染和功能。
2. 移除numSegments配置项
如果同时设置了numSegments和segments数组,可能触发WinWheel的索引冲突逻辑。尝试删除numSegments配置,让库直接从调整后的segments数组长度识别分段数量:
theWheel = new Winwheel({ 'canvasId': 'canvas', // 移除numSegments配置 'outerRadius': data.outer_radius, // ... 其他配置项 'segments': [null, ...data.segments], // ... 动画、pins配置 });
3. 修改WinWheel源码(不推荐)
若要彻底改为0起始索引,可修改库源码中处理segments的逻辑:
- 找到初始化segments数组的代码,移除预留索引0的逻辑
- 将所有遍历、访问分段的代码从1起始改为0起始
但这种方法会增加后续库升级的维护成本,仅在必须完全适配0索引场景时使用。
内容的提问来源于stack exchange,提问作者Moses Barington
相关产品推荐
相关产品推荐

