feat: It wraps text when the text string has \r\n or \n

This commit is contained in:
chenshenhai 2021-08-20 11:32:07 +08:00
parent fc7245e550
commit 6ed412270f
4 changed files with 41 additions and 32 deletions

View file

@ -58,17 +58,17 @@ const data = {
},
{
name: "text-004",
x: 400 - 10,
y: 300 - 10,
w: 200,
h: 100,
x: 300,
y: 240,
w: 290,
h: 120,
type: "text",
desc: {
fontSize: 20,
color: "#333333",
text: "生活就像海洋,只有意志坚强的人,才能到达彼岸。",
text: "Life is like an ocean.\r\nOnly those with strong \nwill can reach the other shore.",
fontFamily: "",
textAlign: "left",
textAlign: "right",
borderRadius: 20,
borderWidth: 2,
borderColor: "#bd0b64",

View file

@ -8,9 +8,13 @@ const data = getData();
const mount = document.querySelector('#mount');
const defaultConf = {
scale: 1.5,
scrollLeft: 100,
scrollTop: 50,
// scale: 1.5,
// scrollLeft: 100,
// scrollTop: 50,
scale: 0,
scrollLeft: 0,
scrollTop: 0,
};
const core = new Core(mount, {
width: 600,

View file

@ -104,16 +104,17 @@
})
core.addElement({
name: "text-001",
x: 50,
x: 40,
y: 100,
w: 200,
w: 240,
h: 80,
type: "text",
desc: {
fontSize: 16,
color: "#3f51b5",
text: "Life is like an ocean.\r\nOnly those with strong will can reach the other shore",
text: "Life is like an ocean.\r\nOnly those with strong \nwill can \r\nreach the other shore.",
fontFamily: 'monospace',
textAlign: 'right',
borderRadius: 8,
borderWidth: 2,
borderColor: "#2196f3",

View file

@ -33,35 +33,39 @@ export function drawText(
fontSize: desc.fontSize,
fontFamily: desc.fontFamily
});
const descText = desc.text.replace(/\r\n/ig, '\n');
const fontHeight = desc.lineHeight || desc.fontSize;
const descTextList = descText.split('\n');
const lines: {text: string, width: number}[] = [];
let lineText = '';
let lineNum = 0;
for (let i = 0; i < desc.text.length; i++) {
if (ctx.measureText(lineText + (desc.text[i] || '')).width < ctx.calcDeviceNum(elem.w)) {
lineText += (desc.text[i] || '');
} else {
lines.push({
text: lineText,
width: ctx.calcScreenNum(ctx.measureText(lineText).width),
});
lineText = (desc.text[i] || '');
lineNum ++;
}
if ((lineNum + 1) * fontHeight > elem.h) {
break;
}
if (lineText && desc.text.length - 1 === i) {
if ((lineNum + 1) * fontHeight < elem.h) {
descTextList.forEach((tempText) => {
let lineText = '';
let lineNum = 0;
for (let i = 0; i < tempText.length; i++) {
if (ctx.measureText(lineText + (tempText[i] || '')).width < ctx.calcDeviceNum(elem.w)) {
lineText += (tempText[i] || '');
} else {
lines.push({
text: lineText,
width: ctx.calcScreenNum(ctx.measureText(lineText).width),
});
lineText = (tempText[i] || '');
lineNum ++;
}
if ((lineNum + 1) * fontHeight > elem.h) {
break;
}
if (lineText && tempText.length - 1 === i) {
if ((lineNum + 1) * fontHeight < elem.h) {
lines.push({
text: lineText,
width: ctx.calcScreenNum(ctx.measureText(lineText).width),
});
break;
}
}
}
}
});
// draw text lines
let _y = elem.y;