Denno
Denno

Reputation: 2178

Origin point for HTML5 canvas fillText

I've just started playing around with HTML5 canvas and specifically, rendering some text on the canvas. I have some super simple code:

const canvas = document.querySelector('canvas');
const c = canvas.getContext('2d');
c.fillText("Sunday", 0, 0);

The problem I'm seeing is that the text isn't visible. However, if I pass 1 for the y value, then I can see the baseline of the text.

This leads me to believe that the origin point for placing elements (or perhaps just text) in the canvas is the bottom left corner of a "box" around whatever is being drawn.. Is this the case?

Upvotes: 1

Views: 820

Answers (2)

kierans
kierans

Reputation: 2213

function drawText(canvas, text, x, y) {
  const ctx = canvas.getContext("2d");

  ctx.font = "36pt sans-serif";
  ctx.fillStyle = "#000000";
  ctx.strokeStyle = ctx.fillStyle;

  const metrics = ctx.measureText(text);
  const width = metrics.width;

  // see https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_text
  const height = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;

  /*
   * Since 'y' in fillText is the position of the baseline, and we want to have the top of
   * the text "box" be at the y argument, we can use the distance from the top of the box
   * to the baseline to set the y argument to fillText, which gives the illusion we've 
   * drawn the text from y.
   */
  ctx.fillText(text, x, y + metrics.actualBoundingBoxAscent);

  /*
   * This can be used to check if our maths is correct by drawing a box around the text.
   */
  //ctx.strokeRect(x, y, width, height);
}

drawText(document.querySelector("canvas"), "Sunday", 0, 0);

Upvotes: 1

Denno
Denno

Reputation: 2178

After a bit more Googlin', I came across textAlign and textBaseline, which can be used to control the origin point used to place the elements.

Thanks stack overflow rubber ducky!

Upvotes: 1

Related Questions