<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div style="width: 400px;height: 400px;background: yellowgreen;">
<canvas id="canvas"></canvas>
</div>
<button id="generateCavans">生成canvas</button>
<script src="../jquery.js"></script>
<script>
$('#generateCavans').click(function(){
var canvas=$('#canvas')[0],
context=canvas.getContext('2d'),
txt='hellow, canvas, welcome ';
context.font = '20px bold 黑体'; // 文字样式
context.fillStyle = '#6d6d6d';
context.textAlign = 'center';
context.textBaseline = 'top';
drawText(context, txt, canvas.width / 2,0,100) //canvas.width / 2 和 context.textAlign = 'center';是居中的必要条件
})
function drawText(context, t, x, y, w) { // context:canvas的2d对象,t:文字,x:显示文字的x坐标,Y:显示文字的y坐标,w:显示文字的宽度
const chr = t.split('');
let rows = 0;
let lineHeight = 0;
let listWidth = 0;
let rowTxt = '';
this.fontRows = 1;
for (let a = 0; a < chr.length; a++) {
rowTxt += chr[a];
listWidth += context.measureText(chr[a]).width; //context.measureText(chr[a]).width是绘制chr[a]的长度
if (t !== rowTxt && listWidth > w) { // canvas文字大于1行,
listWidth = 0;
rows++;
lineHeight++;
this.fontRows = rows;
if (rows === 2) { //最大显示2行,超出部分的加...
context.fillText(rowTxt.slice(0, rowTxt.length - 2) + '...', x, (y + lineHeight) * 17);
return false;
}
context.fillText(rowTxt, x, y + lineHeight * 17);
rowTxt = '';
} else if (a === chr.length - 1) { // 文字绘制完成
rows++;
lineHeight++;
this.fontRows = rows;
context.fillText(rowTxt, x, (y + lineHeight) * 17);
}
}
}
</script>
</body>
</html>
cavans 文字换行
最新推荐文章于 2022-04-24 21:05:35 发布