JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="chart" width="600" height="500" class="lower-canvas"></canvas>
Babel + JSX
class Chart {
constructor(canvasWrapperId = "chart") {
this.canvas = new fabric.Canvas(canvasWrapperId);
// disable object selectable option
this.canvas.selection = false;
// Holds references to all elements
this.shapes = {};
this.markers = [
{label: 'First', val: 150, color: 'green'},
{label: 'Second', val: 300, color: 'red'}
];
}
setup() {
this.shapes.markers = this.drawMarkers();
this.canvas.add(this.shapes.markers);
this.setEvents();
}
setEvents() {
this.canvas.on('mouse:over', (e) => {
if(e.target) {
console.log('Over', e.target);
} else {
console.log('Over: no target');
}
});
this.canvas.on('mouse:down', (e) => {
if(e.target) {
console.log('Down', e.target);
} else {
console.log('Down: no target');
}
});
}
drawLine(data) {
return new fabric.Line([
data.start.x, data.start.y,
data.end.x, data.end.y
],
{stroke: data.color});
}
drawMarker({label, val, color}, {height, margin}) {
const marker = new fabric.Group(),
x = val,
text = label;
const line = this.drawLine({
val,
color,
start: {x,y:90},
end: {x,y: 200}
});
const plate = {height: 24, fullWidth: 70, shortWidth: 20},
indicatorHeight = 5,
plateShape = new fabric.Rect({
width: plate.fullWidth,
height: plate.height,
fill: color,
top: line.top - plate.height - indicatorHeight + 1,
left: x,
originX: "center"
}),
indicator = new fabric.Triangle({
width: 10,
height: indicatorHeight,
fill: color,
top: plateShape.top + plateShape.height + indicatorHeight,
left: x,
originX: "center",
angle: 180
}),
plateLabel = new fabric.Text(text, {
fill: '#FFF',
fontSize: 14,
textAlign: 'center',
top: plateShape.top + 4,
...