JSFiddle - React, Tailwind, and code Playground
by Seetpal Singh
HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<body>
<div id="chartWrapper">
<canvas id="chartJSContainer" width="300" height="400"></canvas>
</div>
</body>
CSS
#chartWrapper {
word-wrap:break-all;
max-width: 100%;
border: 1px solid grey;
padding: 10px;
border-radius: 4px;
}
canvas {
background-color: #eee;
}
JavaScript
const data = {
"labels": [2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020],
"ImprisonedJournalists": [193,221,247,230,234,198,272,271,256,251,274],
"KilledJounalists": [65,62,124,90,99,116,102,80,99,57,62]
}
const dataBase = [
{
label: 'Imprisoned journalists',
data: data.ImprisonedJournalists,
// cubicInterpolationMode: 'monotone',
borderColor: '#E4A429',
backgroundColor: '#E4A429',
radius: 2.5
},
{
label: 'Killed journalists',
data: data.KilledJounalists,
// cubicInterpolationMode: 'monotone',
borderColor: '#2D9BB1',
backgroundColor: '#2D9BB1',
radius: 2.5
}
];
const plugin = {
id: 'custom_canvas_background_color',
beforeDraw: (chart) => {
const ctx = chart.canvas.getContext('2d');
ctx.save();
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = 'white';
var chartHeight = Math.max(chart.height, 400);
ctx.fillRect(0, 0, chart.width, chartHeight);
ctx.restore();
}
};
//To create some padding at bottom of legend
const legendMargin = {
id: 'legendMargin',
beforeInit(chart, legend, options) {
// console.log(chart.legend.fit)
const fitValue = chart.legend.fit;
chart.legend.fit = function fit() {
fitValue.bind(chart.legend)();
return this.height += 20
}
}
};
const options = {
//type: 'bar',
type: 'line',
//pointStyle: 'circle',
plugins: [plugin, legendMargin],
data: {
labels: data.labels,
datasets: dataBase
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
// https://www.chartjs.org/docs/latest/configuration/legend.html
display: true,
//position the legend top left
position: 'top',
align: 'start',
labels: {
/* padding: 10, */
usePointStyle: true,
boxWidth: 9,
color: '#212121',
font: {
family: 'sans-serif',
...