HTML5 canvas fillText的起点

时间:2019-06-29 02:42:49

标签: canvas html5-canvas

我刚刚开始使用HTML5画布,特别是在画布上渲染一些文本。我有一些超级简单的代码:

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

我看到的问题是文本不可见。但是,如果我将1值传递给y,则可以看到文本的基线。

这使我相信在画布上放置元素(或可能只是文本)的原点是围绕所绘制内容的“框”的左下角。 是这样吗?

2 个答案:

答案 0 :(得分:0)

再经过Googlin'之后,我遇到了textAlign和textBaseline,它们可用于控制用于放置元素的原点。

感谢堆栈溢出橡皮鸭!

答案 1 :(得分:0)

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