Javascript 帆布。对齐文本

Javascript 帆布。对齐文本,javascript,canvas,Javascript,Canvas,如果没有文本对齐,这段代码会让我满意。顶线和底线均未在线的中心对齐。你能帮我吗 函数重绘模板(图像、顶线、底线){ var canvas=document.querySelector('canvas'); var ctx=canvas.getContext(“2d”); ctx.textAlign=“中心”; var height=Math.min(image.height,canvas.height); var width=Math.min(image.width,canvas.width)

如果没有文本对齐,这段代码会让我满意。顶线和底线均未在线的中心对齐。你能帮我吗

函数重绘模板(图像、顶线、底线){
var canvas=document.querySelector('canvas');
var ctx=canvas.getContext(“2d”);
ctx.textAlign=“中心”;
var height=Math.min(image.height,canvas.height);
var width=Math.min(image.width,canvas.width);
ctx.drawImage(图像,0,0,宽度,高度);
var font=“bold 24px verdana,无衬线”;
ctx.font=font;
var fillStyle=“白色”;
ctx.fillStyle=fillStyle;
var strokeStyle=“黑色”;
如果(背线){
ctx.fillText(背线,50,50);
ctx.strokeText(背线,50,50);
};
如果(底线){
ctx.fillText(底线,50350);
ctx.strokeText(底线50350);
};
}
//以下代码仅用于示例:
const img=新图像(500500);
img.src=https://api.adorable.io/avatars/500/abott@可爱的.png';
img.onload=函数(){
重绘模因(如“上”、“下”);
}

这是因为画布文本居中对齐,因此每行的左右两端取决于文本长度。可以通过将它们的x坐标设置为宽度的中心来对齐,如下所示:

函数重绘模板(图像、顶线、底线){
var canvas=document.querySelector('canvas');
var ctx=canvas.getContext(“2d”);
ctx.textAlign=“中心”;
var height=Math.min(image.height,canvas.height);
var width=Math.min(image.width,canvas.width);
ctx.drawImage(图像,0,0,宽度,高度);
var font=“bold 24px verdana,无衬线”;
ctx.font=font;
var fillStyle=“白色”;
ctx.fillStyle=fillStyle;
var strokeStyle=“黑色”;
var centerX=宽度/2
如果(背线){
ctx.fillText(背线,中心线,50);
ctx.strokeText(背线,中心线,50);
};
如果(底线){
ctx.fillText(底线,centerX,350);
ctx.strokeText(底线,centerX,350);
};
}
//以下代码仅用于示例:
const img=新图像(500500);
img.src=https://api.adorable.io/avatars/500/abott@可爱的.png';
img.onload=函数(){
重绘模因(如“上”、“下”);
}