Hi,
I’ve put together a custom widget for a gauge meter.
I’ve set up a button to refresh the step, but when refreshing the widget doesn’t change with the new variables.
JS:
// setup
getValue("min", (x) => {
min = x == null ? "" : x;
});
getValue("text_color", (x) => {
text_color = x == null ? "" : x;
});
getValue("lolim_color", (x) => {
lolim_color = x == null ? "" : x;
});
getValue("mid_color", (x) => {
mid_color = x == null ? "" : x;
});
getValue("hilim_color", (x) => {
hilim_color = x == null ? "" : x;
});
getValue("lolim_label", (x) => {
lolim_label = x == null ? "" : x;
});
getValue("mid_label", (x) => {
mid_label = x == null ? "" : x;
});
getValue("hilim_label", (x) => {
hilim_label = x == null ? "" : x;
});
getValue("engunit", (x) => {
engunit = x == null ? "" : x;
});
getValue("max", (x) => {
max = x == null ? "" : x;
});
getValue("lolim", (x) => {
lolim = x == null ? "" : x;
});
getValue("hilim", (x) => {
hilim = x == null ? "" : x;
});
getValue("value", (x) => {
value = x == null ? "" : x;
});
const data = {
labels: [lolim_label, mid_label, hilim_label],
datasets: [
{
label: "Gauge",
data: [lolim, hilim, max],
backgroundColor: [
lolim_color,
mid_color,
hilim_color,
],
needleValue: value,
borderColor: "white",
borderWidth: 2,
cutout: "95%",
circumference: 180,
rotation: 270,
borderRadius: 5,
},
],
};
//gaugeNeedle
const gaugeNeedle = {
id: "gaugeNeedle",
afterDatasetDraw(chart, args, options) {
const {
ctx,
config,
data,
chartArea: { top, right, bottom, left, width, height },
} = chart;
ctx.save();
const needleValue = data.datasets[0].needleValue;
const dataTotal = data.datasets[0].data.reduce((a, b) => a + b, 0);
var angle = Math.PI + (needleValue/max) * Math.PI;
console.log(angle);
const cx = width / 2;
const cy = chart._metasets[0].data[0].y;
//needle
ctx.translate(cx, cy);
ctx.rotate(angle);
ctx.beginPath();
ctx.moveTo(0, -2);
ctx.lineTo(height - ctx.canvas.offsetTop - 160, 0); // change 160 value if the needle size gets changed
ctx.lineTo(0, 2);
ctx.fillStyle = text_color;
ctx.fill();
//needle dot
ctx.translate(-cx, -cy);
ctx.beginPath();
ctx.arc(cx, cy, 5, 0, 10);
ctx.fill();
ctx.restore();
//text
ctx.font = "24px Ubuntu";
ctx.fillStyle = text_color;
ctx.fillText(needleValue +" "+ engunit, cx, cy + 50);
ctx.font = "14px Ubuntu";
ctx.fillText(min, 55, cy);
ctx.fillText(max/2, cx, 155);
ctx.fillText(max, (width-55), cy); // change values if the position gets changed
ctx.textAlign = "center";
ctx.restore();
},
};
// config
const config = {
type: "doughnut",
data,
options: {
plugins: {
legend: {
display: false,
},
tooltip: {
yAlign: "bottom",
displayColors: false,
callbacks: {
label: function (tooltipItem, data, value) {
return tooltipItem.label;
},
},
},
},
},
plugins: [gaugeNeedle],
};
// render init block
const myChart = new Chart(document.getElementById("gauge"), config);