Today I’m going to share another snippet for Chart.js, that you can use to put a watermark image or logo in charts.
To do that, I’ll create a small plugin. I’ll register the plugin globally to apply it on all charts. Though, you can apply it on chart instance as you want. You can read details on chart.js plugins from here.
We’ll add the script for the watermark inside the afterRender() callback function which is called after a chart has been completely rendered.
Lets create a canvas.
And apply the javascript.
const chart_watermark = {
id: 'chart_watermark',
afterDraw: (chart) => {
const image = new Image();
image.src = 'https://wickedev.com/wp-content/uploads/2020/08/logo-dark-alt.png';
if (image.complete) {
const image_height = 82;
const image_width = 125;
const ctx = chart.ctx;
const x = chart.chartArea.width - image_width;
const y = chart.chartArea.height - image_height;
ctx.globalAlpha = 0.35;
ctx.drawImage(image, x, y, image_width, image_height);
ctx.globalAlpha = 1;
} else {
image.onload = () => chart.draw();
}
}
};
Chart.register(chart_watermark);
new Chart("mychart", {
type: 'bar',
data: {
labels: ["Apples", "Oranges", "Pineapples", "Water Malones", "Mangoes", "Bannanas"],
datasets: [{
label: '# of Sells',
data: [100, 125, 99, 200, 180, 136],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 2
}]
},
});
Very good article. I certainly appreciate this website. Keep writing!