JSFiddle - React, Tailwind, and code Playground
by m1erickson
HTML
<p>Click on a bar in the chart</p>
<canvas id="canvas" width=300 height=300></canvas>
CSS
body {
background-color: ivory;
}
canvas {
border:1px solid red;
}
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var barWidth = 30;
var barSpacing = 15;
var leftMargin = 20;
var bars = []
bars.push({
height: 150,
color: "blue",
x: null,
y: null,
right: null,
bottom: null
});
bars.push({
height: 75,
color: "green",
x: null,
y: null,
right: null,
bottom: null
});
bars.push({
height: 125,
color: "gold",
x: null,
y: null,
right: null,
bottom: null
});
for (var i = 0; i < bars.length; i++) {
bar = bars[i];
bar.x = leftMargin + (barWidth + barSpacing) * i;
bar.y = canvas.height - bar.height;
bar.width = barWidth;
bar.right = bar.x + barWidth;
bar.bottom = canvas.height;
}
drawBarchart();
function drawBarchart() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "skyblue";
ctx.fill();
for (var i = 0; i < bars.length; i++) {
bar = bars[i];
ctx.beginPath();
ctx.rect(bar.x, bar.y, bar.width, bar.height);
ctx.fillStyle = bar.color;
ctx.fill();
ctx.stroke()
}
}
function handleMouseDown(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mousedown stuff here
for (var i = 0; i < bars.length; i++) {
var bar = bars[i];
if (mouseX >= bar.x && mouseX <= bar.right && mouseY >= bar.y && mouseY <= bar.bottom) {
alert("Clicked on [" + bar.color.toUpperCase() + "] so open another chart!");
}
}
}
$("#canvas").mousedown(function (e) {
handleMouseDown(e);
});