Answer the question
In order to leave comments, you need to log in
How can I display text with different sizes inside my canvas element?
I have a function that displays charts on a page
function initCanvasDiagrams() {
let canvas = document.querySelectorAll("canvas");
canvas.forEach((el, index) => {
let ctx = el.getContext("2d");
let lastend = 0;
let myTotal = 0;
let data = [30, 15, 30, 25];
let myColor = ['#1DCDF0', '#00BDBD', '#0D94E0', '#0D53A3'];
let labels = ['30%', '15', '30', '25'];
for (let e = 0; e < data.length; e++) {
myTotal += data[e];
}
// make the chart 10 px smaller to fit on canvas
let off = 10
let w = (el.width - off) / 2
let h = (el.height - off) / 2
for (let i = 0; i < data.length; i++) {
ctx.fillStyle = myColor[i];
ctx.beginPath();
ctx.moveTo(w, h);
let len = (data[i] / myTotal) * 2 * Math.PI
let r = h - off / 2
ctx.arc(w, h, r, lastend, lastend + len, false);
ctx.lineTo(w, h);
ctx.fill();
ctx.fillStyle = 'white';
ctx.font = 'bold 24px sans-serif';
ctx.textAlign = "center";
ctx.textBaseline = "middle";
let mid = lastend + len / 2
ctx.fillText(labels[i], w + Math.cos(mid) * (r / 2), h + Math.sin(mid) * (r / 2));
lastend += Math.PI * 2 * (data[i] / myTotal);
}
})
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question