JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-dragdata@2.2.4/dist/chartjs-plugin-dragdata.min.js"></script>
<canvas id="chartJSContainer" style="height: 400px; width: 500px;"></canvas>
JavaScript
// this simplistic plugin assumes there is only 1 (!) dataset present in the chart
// furthermore, it assumes the chart to be a scatter chart
const ChartJSClickPlugin = {
id: 'click',
afterInit: function (chartInstance) {
// start listening for double-click events on the charts canvas
chartInstance.canvas.addEventListener("dblclick", e => {
// query corresponding x/y values for the click event
let x, y
if (e.touches) {
x = chartInstance.scales.x.getValueForPixel(e.touches[0].clientX - chartInstance.canvas.getBoundingClientRect().left)
y = chartInstance.scales.y.getValueForPixel(e.touches[0].clientY - chartInstance.canvas.getBoundingClientRect().top)
} else {
x = chartInstance.scales.x.getValueForPixel(e.clientX - chartInstance.canvas.getBoundingClientRect().left)
y = chartInstance.scales.y.getValueForPixel(e.clientY - chartInstance.canvas.getBoundingClientRect().top)
}
// find the fitting index where the new datapoint should be inserted to
// note that only the x-axis is relevant here, as the line is read from left-to-right
const data = chartInstance.data.datasets[0].data
//
let indexToInsert = data.findIndex((point,index,arr) => {
if (index === 0 && x < point.x) {
// insert at the beginning
return 0
}
// insert at the first array position where our new datapoint has a greater value than the previous entry
return point.x > x
})
// insert the new datapoint accordingly
data.splice(indexToInsert,0,{x,y})
// update the chart, without animation
chartInstance.update('none')
// you may switch to the following line if you prefer animations
//chartInstance.update()
})
}
}
Chart.register(ChartJSClickPlugin)
let storedValue;
var options = {
type: 'scatter',
...