Search code examples
javascriptcsshtml5-canvascss-transforms

How to scale text when drawing to canvas?


I am scaling text using CSS transform scale eg

transform: scale(2, 4);
fontSize: 20px // do I need to include fontSize?

I also need to draw the same text on a canvas element

function draw() {
  const ctx = document.getElementById('canvas').getContext('2d');
  ctx.font = '20px serif';
  ctx.fillText('Hello world', 10, 50);
}

How should I scale the text in the above js function? I've hardcoded the font size 20px but how would I use the scale values of 2 and 4?


Solution

  • You can set the context of the canvas to have scaling by calling the context's scale function.

    Here's an example:

    function draw() {
      const ctx = document.getElementById('canvas').getContext('2d');
      ctx.font = '20px serif';
      ctx.scale(2, 4);
      ctx.fillText('Hello world', 10, 50);
    }
    window.onload = draw;
    <canvas id="canvas" width="250" height="250"></canvas>

    Don't forget to reset the scale when you've finished drawing the text.