{
const canvas = document.createElement('canvas');
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
const ctx = canvas.getContext('2d');
const barWidth = Math.floor((width - margin.left - margin.right) / data.length) / 2;
const gap = barWidth;
const dataMax = Math.max(...data.map(datum => datum.percent));
const barHeight = (value) => {
return (height - margin.top - margin.bottom) * (value / dataMax);
}
const xScale = (i) => {
return (barWidth + gap) * i + margin.left + barWidth / 2;
}
const yScale = (value) => {
return (height - margin.top - margin.bottom) - barHeight(value) + margin.top;
}
const drawBar = (datum, i) => {
ctx.save();
ctx.fillStyle = 'steelblue';
ctx.fillRect(xScale(i), yScale(datum.percent), barWidth, barHeight(datum.percent));
ctx.restore();
}
const drawLabel = (datum, i) => {
ctx.save();
ctx.font = '14px sans-serif';
ctx.textAlign = 'center';
ctx.fillStyle = '#333';
ctx.fillText(`${datum.percent}%`, xScale(i) + barWidth / 2, yScale(datum.percent) - 5);
ctx.restore();
}
const drawXAxisTick = (i) => {
ctx.save();
ctx.strokeStyle = '#000';
ctx.moveTo(xScale(i) + barWidth / 2, height - margin.bottom + 1);
ctx.lineTo(xScale(i) + barWidth / 2, height - margin.bottom + 6);
ctx.stroke();
ctx.restore();
}
const drawXAxisLabel = (label, i) => {
ctx.save();
ctx.font = '14px sans-serif';
ctx.textAlign = 'center';
ctx.fillStyle = '#333';
ctx.fillText(label, xScale(i) + barWidth / 2, height - margin.bottom + 20);
ctx.stroke();
ctx.restore();
}
const drawXAxisLine = () => {
ctx.save();
ctx.strokeStyle = '#000';
ctx.moveTo(margin.left, height - margin.bottom + 1);
ctx.lineTo(width - margin.right, height - margin.bottom + 1);
ctx.stroke();
ctx.restore();
}
const drawYAxis = () => {
const yLabels = [0, 10, 20, 30, 40, 50, 60];
ctx.save();
ctx.strokeStyle = '#000';
ctx.textBaseline = 'middle';
yLabels.forEach(label => {
ctx.moveTo(margin.left - 5, yScale(label) + 1);
ctx.lineTo(margin.left - 10, yScale(label) + 1);
ctx.stroke();
ctx.fillText(label, margin.left - 12 - ctx.measureText(label).width, yScale(label) + 1);
})
ctx.restore();
}
const drawYTitle = () => {
ctx.save();
ctx.strokeStyle = '#000';
ctx.font = '14px sans-serif';
ctx.fillText('Percentage(%)', 0, 20);
ctx.restore();
}
data.forEach((datum, i) => {
drawBar(datum, i);
drawLabel(datum, i);
drawXAxisTick(i);
drawXAxisLabel(datum.browser, i);
})
drawXAxisLine();
drawYAxis();
drawYTitle();
return canvas;
}