封装
function fillFeedText({
ctx, text, x, y, maxWidth, lineHeight, color, size
}) {
ctx.setFontSize(size);
ctx.setFillStyle(color);
const words = text.split('');
let line = '';
const lines = [];
for (let i = 0; i < words.length; i++) {
const word = words[i];
const testLine = line + word;
const metrics = ctx.measureText(testLine);
if (metrics.width > maxWidth && i > 0) {
lines.push(line);
line = word;
} else {
line = testLine;
}
};
lines.push(line);
lines.forEach((line, index) => {
ctx.fillText(line, x, y + ((index++) * lineHeight), maxWidth);
});
}
使用
const text = ["时间:" + Tool.now(), state.address];
text.forEach((line, index) => {
fillFeedText({
ctx,
text: line,
x: padding,
y: state.height * 0.91 + ((index++) * lineHeight),
maxWidth: state.width - padding,
lineHeight,
color: '#FFFFFF',
size: 10
})
});
效果