鼠标单击Chart.js创建数据点

问题描述 投票:1回答:1

我是Chart.js和JavaScript的新手。目前正在使用折线图,现在我想将自定义数据点添加到鼠标单击事件中(当我按下数据集上的某个位置时,它会获取Y轴的当前值并使用该值创建一个数据点那个地方)。我从http://www.chartjs.org/samples/latest/charts/line/basic.html获取代码并尝试修改它。这是我当前图表的链接:https://i.stack.imgur.com/M9MF1.jpg

我使用基本的chart.bundle.js库,并使用D3.js库使数据点可拖动。

尝试使用以下代码实现每次鼠标点击的创建,但似乎到目前为止它并不好。

document.getElementById('canvas').onclick = function(e){
    //getting value by pressing on dataset 
     value = chartInstance.scales[scale].getValueForPixel(e.clientY)
     //trying to create dataPoint 
     myLineChart.points.push(new this.PointClass({
                    y: value;
                    strokeColor: this.datasets[datasetIndex].pointStrokeColor,
                    fillColor: this.datasets[datasetIndex].pointColor
                    }));
    //after all updating my chart
    chartInstance.Update(0)
};

也许有人可以解释一下这个库以及它如何创建数据点的更多信息?

javascript dataset chart.js points mouseclick-event
1个回答
0
投票

图表中的每个新点都是数据,因此您需要在数据(chartData.data.dataset [])数组中添加该点。而不是添加myLineChart.points我不确定你为什么使用你应该在数据数组中添加数据点,并且应该在chartOptions.scales.yAxes中指定颜色等UI装饰[数组。因此,为了在图表中添加点,请使用:

// here i is the corresponding parameter for which you want to add the new point
chartInstance.data.datasets[i].push(value); 
chartInstance.update();
© www.soinside.com 2019 - 2024. All rights reserved.