A
A
Andy Oker2020-12-06 14:34:56
JavaScript
Andy Oker, 2020-12-06 14:34:56

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);
    }
  })
}


Values ​​for a specific area are pulled from the labels array. I want the "%" character to be displayed after this value, but with a smaller font-siz. How would it be implemented?

I will be glad to any feedback!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WbICHA, 2020-12-06
@WblCHA

I want the "%" symbol to be displayed after this value, but with a smaller font-siz. How would it be implemented?

I don't even know what to do about it?
Hmm, maybe change the font-size?
ctx.font = 'bold 24px sans-serif';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question