html 在JavaScript中,当我将文本绘制到画布上时,如何将其居中?

dddzy1tm  于 8个月前  发布在  Java
关注(0)|答案(1)|浏览(62)

在JavaScript中,我可以绘制对齐到左边距的文本。我正试着把它和画布中心对齐。
Canvas维度直接从html canvas读取

<canvas id="sketch" width=390 height=844></canvas>

并用于定义表示画布的水平中心的变量centreX

const cnv = document.getElementById('sketch');
    const ctx = cnv.getContext('2d');
    const centreX = cnv.width / 2;
    const centreY = cnv.height / 2;

如果将state的值绘制到画布上,它将显示为左对齐

let state = 1;

    function drawStateTextLeft(state) {
        const text = `${state + 1}`;
        ctx.fillText(`${state+1}`, 10, 30);                 // text appears
    }

我假设绘制与画布中心对齐的相同文本是一个简单的问题,即测量文本的宽度,并从水平中心开始偏移文本宽度的一半。
例如

function drawStateTextCentre(state) {
        const text = `${state + 1}`;
        const textWidth = ctx.measureText(text).width;  // Calculate the width of the text
        var textX = centerX - textWidth / 2;                // Calculate the X position to center the text
//      alert(centreX + "\t" + textWidth + ”\t” + textX);                   
        ctx.fillText(text, textX, 30);                      // text does not appear
    }

alert显示centreX为195,textWidth为13.3434,textX为181.656。但文本没有出现。
我做错了什么?

wnavrhmk

wnavrhmk1#

看起来你已经走上了正确的道路,可以将文本水平地居中在画布上。但是,您的代码中有一个小的错别字。您正在使用ctxO来测量文本宽度,但您应该使用ctx,这是您的画布2D上下文。

function drawStateTextCentre(state) {
    const text = `${state + 1}`;
    const textWidth = ctx.measureText(text).width;  // Use ctx to measure text width
    const textX = centreX - textWidth / 2;         // Corrected variable name
    ctx.fillText(text, textX, 30);
}

相关问题