Measure Ruler in JavaScript
Using ApexCharts with JavaScript
This Measure Ruler example uses ApexCharts.js directly in JavaScript, with no wrapper component.
Install it with npm install apexcharts, then mount the chart with new ApexCharts(element, options).render().
function series() {
var out = []
var v = 100
for (var i = 0; i < 60; i++) {
v += 2 + Math.sin(i / 5) * 3
out.push([i, Math.round(v)])
}
return out
}
var options = {
series: [{ name: 'Price', data: series() }],
chart: {
id: 'price',
type: 'area',
height: 380,
fontFamily: 'Helvetica, Arial, sans-serif',
animations: { enabled: false },
measure: { enabled: true, pinOnRelease: true },
toolbar: { show: true, autoSelected: 'measure' },
zoom: { enabled: true, type: 'x' },
},
stroke: { width: 2, curve: 'straight' },
dataLabels: { enabled: false },
title: { text: 'Price (measure any move)', align: 'left' },
xaxis: { type: 'numeric', title: { text: 'Session' } },
yaxis: { title: { text: 'Price' }, decimalsInFloat: 0 },
}
var chart = new ApexCharts(document.querySelector('#chart'), options)
chart.render()
// The ruler tool is pre-selected via toolbar.autoSelected: 'measure', so the
// plot is already armed on load -- just drag. The toolbar icon toggles it (and
// the 'm' key still works); no custom wiring needed here.
var readout = document.getElementById('mz-readout')
document.getElementById('mz-clear').addEventListener('click', function () {
chart.clearMeasures()
})
chart.addEventListener('measured', function (c, o) {
readout.textContent =
'dx=' +
Number(o.dx).toFixed(2) +
' dy=' +
Number(o.dy).toFixed(2) +
' (' +
(o.percentChange >= 0 ? '+' : '') +
Number(o.percentChange).toFixed(1) +
'%)'
})