Canvas tooltip
by Alon Rotem
HTML
<canvas id="chart-canvas"></canvas>
CSS
#chart-canvas {
border: 1px solid black;
}
JavaScript
var canvas = document.getElementById("chart-canvas");
canvas.width = window.innerWidth - 100;
canvas. height = window.innerHeight - 100;
var ctx = canvas.getContext('2d');
var cursor = {
x: undefined,
y: undefined
};
canvas.addEventListener("mousemove", (e) => {
cursor.x = e.offsetX;
cursor.y = e.offsetY;
});
canvas.addEventListener ("mouseout", (e) => {
cursor.x = undefined;
cursor.y = undefined;
}, false);
function drawTooltip(text, px_height, text_color, fill_color, border_color)
{
var
tip_height = 10,
tip_width = 10,
tooltip_y_offset = 20,
tooltip_x_offset = 10;
if(border_color)
ctx.strokeStyle = border_color;
ctx.fillStyle = fill_color;
ctx.lineWidth = 1;
text_margin = 30;
ctx.font = px_height + "px Arial";
ctx.textAlign = "center";
var tooltip_width = ctx.measureText(text).width + text_margin;
var tooltip_height = px_height + text_margin;
var tooltip_shift_x = 0;
var beyond_left_edge = (((tooltip_width/2) - (tip_width)) - cursor.x);
var beyond_right_edge = (canvas.width - (cursor.x + (tooltip_width/2) + tip_width));
if(beyond_left_edge > 0)
{
tooltip_shift_x = beyond_left_edge;
}
else if(beyond_right_edge < 0)
{
tooltip_shift_x = beyond_right_edge;
}
/*
x3,y3
x1,y1 / x8,y8 / \ x5,y5
[------------------/ \------------------]
| x2,y2 x4,y4 |
| |
| |
[-----------------------------------------]
x7,y7 x6,y6
*/
ctx.beginPath();
if (cursor.x && cursor.y){
/*x1,y1*/ctx.moveTo(cursor.x-(tooltip_width/2) + tooltip_x_offset+ tooltip_shift_x, cursor.y + tip_height + tooltip_y_offset);
/*x2,y2*/ctx.lineTo(tooltip_shift_x+ cursor.x - (tip_width/2) + tooltip_x_offset - tooltip_shift_x, cursor.y + tip_height +...