在Chart JS中创建自定义点元素遇到的问题
问题描述
我希望通过继承默认的PointElement来实现自定义CustomPointElement,但自定义点的代码从未被调用。我不确定该如何注册它,也不确定当前的做法是否正确,图表仍在使用默认的绘制逻辑,从未触发CustomPointElement。
用户提供的代码:
class CustomPointElement extends Chart.elements.PointElement { draw(ctx, area) { console.log("custom draw") super.draw(ctx, area); // custom drawing logic here } } Chart.register({ id: 'customPointElement', element: CustomPointElement, }); const ctx = document.getElementById('myChart'); // create a new line chart in chartJS const myChart = new Chart(ctx, { type: 'line', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], borderWidth: 1, pointRadius: 10, }] }, })
解决方案
问题出在自定义元素的注册方式错误,以及未明确指定数据集使用该元素,具体修正方法如下:
1. 正确注册自定义元素
Chart.js注册自定义元素时,需要通过type字段指定元素类型,而非仅用id:
- 若要全局替换默认的点元素,将
type设为'point'(默认点元素的类型名); - 若要新增一种自定义点元素类型,则使用自定义的类型名(比如
'customPoint')。
全局替换默认点元素的注册代码
Chart.register({ type: 'point', // 指定覆盖默认的point类型 element: CustomPointElement, });
新增自定义点元素类型的注册代码
Chart.register({ type: 'customPoint', // 自定义类型名 element: CustomPointElement, });
2. 指定数据集使用自定义元素
如果是新增自定义类型,必须在数据集配置中通过pointElement指定使用该自定义类型:
datasets: [{ // ... 其他配置项 pointElement: 'customPoint' // 对应注册时的自定义类型名 }]
完整修正示例
示例1:全局替换默认点元素
class CustomPointElement extends Chart.elements.PointElement { draw(ctx, area) { console.log("custom draw") super.draw(ctx, area); // 自定义绘制逻辑示例:在点中心加白色小圆 ctx.save(); ctx.beginPath(); ctx.arc(this.x, this.y, this.options.radius / 2, 0, Math.PI * 2); ctx.fillStyle = 'white'; ctx.fill(); ctx.restore(); } } // 注册时覆盖默认point元素 Chart.register({ type: 'point', element: CustomPointElement, }); const ctx = document.getElementById('myChart'); const myChart = new Chart(ctx, { type: 'line', data: { labels: ['红', '蓝', '黄', '绿', '紫', '橙'], datasets: [{ label: '票数', data: [12, 19, 3, 5, 2, 3], borderWidth: 1, pointRadius: 10, }] }, })
示例2:使用新增的自定义点元素类型
class CustomPointElement extends Chart.elements.PointElement { draw(ctx, area) { console.log("custom draw") super.draw(ctx, area); // 自定义绘制逻辑 } } // 注册自定义类型 Chart.register({ type: 'customPoint', element: CustomPointElement, }); const ctx = document.getElementById('myChart'); const myChart = new Chart(ctx, { type: 'line', data: { labels: ['红', '蓝', '黄', '绿', '紫', '橙'], datasets: [{ label: '票数', data: [12, 19, 3, 5, 2, 3], borderWidth: 1, pointRadius: 10, pointElement: 'customPoint' // 指定使用自定义元素 }] }, })
内容的提问来源于stack exchange,提问作者user13576487
相关产品推荐
相关产品推荐

