There is a chartjs-plugin-dragdata that enables dragging items in the chart. However, it is not working in my Angular project so I decided to achieve the same functionality manually.
This is how the result looks like:
Our plan
I want to click
to select a point then start dragging it. As we know,
Drag = mouseDown -> mouseMove -> mouseUp
Hence, the interaction should be:
Let’s code
🥇Step 1. Create a line chart
We first create a <canvas>
with a template variable #chartCanvas
. Template variables enable us to get reference to the html element.
With the template variable, we can get the element using @ViewChild
. The element reference exists after Angular initializes the component’s views and child views, which is AfterViewInit
. (Read more about Angular lifecycle hooks here)
In ngAfterViewInit
, we will create the line chart with an onClick
event, determining which point is now selected. Also, the chart will listen to onMouseDown
and onMouseUp
. These two mouseEvents will decide when to enable the onMouseMove
event 🐁
🥈Step 2. Set active points in onClick and register events
Referencing the solution provided here, our final .ts
file will be:
And yeah, that’s all 🥳
💬 If you do not want to use getRelativePosition
function from chart.js/helpers
, you can simply pass e.offsetY
to the map function:
var yValue = this.map(e.offsetY, chartArea.bottom, chartArea.top, yAxis.min, yAxis.max);
because mouseEvent
’s offsetY is the offset in the Y coordinate of the mouse pointer between that event and the padding edge of the target node 🧡