乐趣区

canvas绘制多行文字

代码如下:
let Canvas = document.createElement(‘canvas’);
let ctx = Canvas.getContext(“2d”);
let scaleBy = 2;
let fontSize = 12;
let lineheight = fontSize * scaleBy * 1.4; // 行高为 size1.4 倍
let {x, y} = {30, 10};
let line = ‘ 你好 #该我换行了# 再见 ’
ctx.textAlign = ‘left’; // 可以选择 center right
ctx.font = fontSize * scaleBy + “px PingFangSC”;

line.split(‘#’).forEach((item, i) => {
ctx.fillText(item, x3 * scaleBy, y3 * scaleBy + (i * lineheight));
})
let nodeImg = document.createElement(“img”);
nodeImg.src = Canvas.toDataURL();
document.body.appendChild(nodeImg)

退出移动版