居中 HTML5 响应式 Canvas 文本

Centering HTML5 Responsive Canvas Text

我正在使用以下功能允许应用程序用户在他们的 canvas 照片上插入文本。它按预期工作,文本在靠近边缘时缩小,但如果文本不大于 canvas.

,我无法弄清楚如何使文本居中
var canvas4 = document.getElementById("canvas4");
        var ctx4 = canvas4.getContext("2d");

        canvas4.width = $(window).width();
        canvas4.height = $(window).height();

        var txt = value,
            tw,
            oc, octx;
        ctx4.font = '40px sans-serif';
        ctx4.fillStyle = 'blue';
        ctx4.textBaseline = 'top';
        ctx4.globalAlpha = 0.50;

        tw = ctx4.measureText(txt).width;

        if (tw > canvas4.width - 20) {
                oc = document.createElement('canvas');
                octx = oc.getContext('2d');
                oc.width = tw;
                oc.height = parseInt(ctx4.font, 10) * 1.2;
                octx.font = '40px sans-serif';
                octx.textBaseline = 'top';
                octx.fillText(txt, 0, 0);
                ctx4.drawImage(oc, 10, canvas4.height - 100, canvas4.width - 20, (canvas4.width - 20) / tw * oc.height);
        } else {
            ctx4.fillText(txt, 10, canvas4.height - 100);
        };

我尝试过文本对齐,例如 ctx4.textAlign = 'center, canvas4.width / 2, canvas4.height - 100';

ctx.fillText("Your text here",canvas.width/2, canvas.height/2); 

我没有使用 canvas 元素的经验。但这会帮助你。

textAlign就一个字,"center"。剩下的在你的 fillText 电话中。

ctx4.textAlign = 'center';
ctx4.fillText(txt, canvas4.width / 2, canvas4.height - 100);

textAlign 设置为 "center" 会使文本的中心出现在 fillText 调用中指定的点。如果该点以 canvas 为中心,则整个文本将以 canvas.

为中心