Search code examples
javascriptcanvasaspect-ratiotext-size

JavaScript Canvas Text Ratio


i have a fixed sized Canvas (850x400px) and when I'm adding text to this canvas, its scaled up in a weird way, and I don't know why.

If I do not set the canvas to a specific height/width, the text appears normal, why is that?

export function addText() {
  var canvas = document.getElementById("canvas"); // 850x400px
  var ctx = canvas.getContext("2d");
  var y = 1 * 20 + 20;

  var text = {
    text: "ABC",
    x: 20,
    y: y
  };

  ctx.font = "40px consolas";
  text.width = ctx.measureText(text.text).width;
  text.height = 80;
  ctx.fillText(text.text, text.x, text.y);
}

This is what the text in the canvas field will look like:

enter image description here

How can I insert text that is scaled just like normal 40px font?


Solution

  • I think you have not specified the width and height of the canvas HTML element itself, try:

    addText();
    
    function addText() {
      var canvas = document.getElementById("canvas"); // 850x400px
      var ctx = canvas.getContext("2d");
      var y = 1 * 20 + 20;
    
      var text = {
        text: "ABC",
        x: 20,
        y: y
      };
    
      ctx.font = "40px consolas";
      text.width = ctx.measureText(text.text).width;
      text.height = 80;
      ctx.fillText(text.text, text.x, text.y);
    }
    <canvas id="canvas" width="850" height="400" style="background: red"></canvas>

    Update

    Another option is to set the width and height programmatically, this will prevent the zooming:

    let canvas = document.getElementById("canvas");
    
    canvas.height = window.innerHeight;
    canvas.width = window.innerWidth;
    

    I used the window width and height, but any other element will do it.