ctx.fillText 没有做任何事情

ctx.fillText isn't doing anything

我正在制作一个网站,我希望在该网站的矩形中间写上文字。文本将是一个从 1 到 100 的数字。出于某种原因 ctx.fillText() 没有做任何事情。我的 canvas 不小。它和上面绘制的图像一样大。

代码:

const ctx = editCanvas.getContext("2d");

const backgroundImage = new Image();

backgroundImage.src = "some random path";

backgroundImage.onload = () => {
    editCanvas.width = backgroundImage.width;
    editCanvas.height = backgroundImage.height;

    ctx.drawImage(backgroundImage, 0, 0);
};

function drawSelectionRect(
    text,
    { x, y, width, height },
    { strokeWidth, lineDash, strokeColor },
    fillColor
) {
    ctx.lineWidth = strokeWidth;
    ctx.setLineDash(lineDash);
    ctx.strokeStyle = strokeColor;

    ctx.strokeRect(x, y, width, height);

    ctx.fillStyle = fillColor;

    ctx.fillRect(x, y, width, height);

    const { width: textWidth, height: textHeight } = ctx.measureText(text);

    ctx.fillStyle = "#000";
    ctx.font = "16px sans-serif";

    ctx.fillText(
        text,
        x + width / 2 - textWidth / 2,
        y + height / 2 - textHeight / 2,
        width
    );
}

您可能需要仔细检查 measureText 的 return:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/measureText#return_value
那里没有任何身高相关...

如果我们删除那些 textWidth 和 textHeight,您的 drawSelectionRect 函数就会起作用。

我相信你想要完成的是对齐文本,也许用这些,你可以做到:

这是你的代码

const editCanvas = document.getElementById('c');
const ctx = editCanvas.getContext("2d");

function drawSelectionRect(
    text,
    { x, y, width, height },
    { strokeWidth, lineDash, strokeColor },
    fillColor
) {
    ctx.lineWidth = strokeWidth;
    ctx.setLineDash(lineDash);
    ctx.strokeStyle = strokeColor;

    ctx.strokeRect(x, y, width, height);
    ctx.fillStyle = fillColor;
    ctx.fillRect(x, y, width, height);

    console.log(ctx.measureText(text))
    
    ctx.fillStyle = "#000";
    ctx.font = "16px sans-serif";
    ctx.textBaseline = "middle";
    ctx.textAlign = "center";
    ctx.fillText(
        text,
        x + width / 2,
        y + height / 2,
        width
    );
}

drawSelectionRect(
  "ooo", 
  {x:2, y:2, width:40, height:40}, 
  {strokeWidth:3, lineDash:[0], strokeColor: "black"}, 
  "red"
)
<canvas id="c"></canvas>

记住console.log(是你的朋友,当你不确定发生了什么时,输出你正在使用的变量,看看有什么不是你计划的