canvas 绘制包含10个换行(‘\n’)文字例子,要求可以设置行高,文字最后整体在canvas的高度垂直居中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas Text Example</title>
<style>
#mycanvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="800" height="600"></canvas>
<script type='text/javascript'>
let canvas = document.getElementById("mycanvas");
let ctx = canvas.getContext('2d');
// 文字内容和行高
const textContent = "This is line\n".repeat(10);
const lineHeight = 30;
// 将字符串分割成多行
const lines = textContent.split('\n').filter(Boolean);
// 计算总体需要的高度(文字数量 * 行高)
totalHeight = lines.length * lineHeight;
// 计算开始位置, 垂直居中整体文字
startY = (canvas.height - totalHeight) /2;
ctx.font ='20px Arial';
ctx.textBaseline='top';
for(let i=0; i< lines.length; i++){
// 绘制每一行, 并增加偏移量.
ctx.fillText(lines[i],50,startY+ lineHeight*i)
}
</script>
</body>
</html>