Skip to content

Commit

Permalink
Fix (drawText): Unaligned code when line feed (#145)
Browse files Browse the repository at this point in the history
  • Loading branch information
pioupia committed Mar 21, 2024
1 parent 18ff1fb commit a5c57aa
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 18 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "carbonimg",
"version": "1.8.2-BETA",
"version": "1.8.3-BETA",
"description": "A Carbon image generator from code",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
15 changes: 6 additions & 9 deletions src/util/generateImage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,27 +19,24 @@ function drawText(
const charWidth = ctx.measureText(text[i] as string).width;
const isBreakLine = text[i] === "\n";

if (text[i] === " " || isBreakLine) lastIndexSpace = i + 1;
if (text[i] === " " || isBreakLine)
lastIndexSpace = i + 1;

if ((lastX + charWidth + ImageSizes.marginRight > width - options.lineNumberWidth) || isBreakLine) {
const sentenceWidth = ctx.measureText(
text.slice(0, lastIndexSpace)
).width;
let cuttingIndex = i;
if (sentenceWidth + lastY + ImageSizes.marginRight <= width - options.lineNumberWidth) {
cuttingIndex = lastIndexSpace;
}

const printedText = text.slice(0, cuttingIndex)?.replace(/\n/g, "");
const printedText = text.slice(0, lastIndexSpace)?.replace(/\n/g, "");
ctx.fillText(
printedText,
lastX - ctx.measureText(printedText).width,
lastY
);

text = text.slice(cuttingIndex);
textLength -= cuttingIndex;
i -= cuttingIndex;
text = text.slice(lastIndexSpace);
textLength -= lastIndexSpace;
i -= lastIndexSpace;

lastY += ImageSizes.textLineHeight + charHeight;
lastX = backgroundPadding.left + charWidth;
Expand Down
13 changes: 5 additions & 8 deletions src/util/sizes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,20 +79,17 @@ function getHeightOfAText(
const charWidth = ctx.measureText(text[i] as string).width;
const isBreakLine = text[i] === "\n";

if (text[i] === " " || isBreakLine) lastIndexSpace = i + 1;
if (text[i] === " " || isBreakLine)
lastIndexSpace = i + 1;

if ((lastX + charWidth + ImageSizes.marginRight > width - lineNumberWidth) || isBreakLine) {
const sentenceWidth = ctx.measureText(
text.slice(0, lastIndexSpace)
).width;
let cuttingIndex = i;
if (sentenceWidth + lastY + ImageSizes.marginRight <= width - lineNumberWidth) {
cuttingIndex = lastIndexSpace;
}

text = text.slice(cuttingIndex);
textLength -= cuttingIndex;
i -= cuttingIndex;
text = text.slice(lastIndexSpace);
textLength -= lastIndexSpace;
i -= lastIndexSpace;

lastY += ImageSizes.textLineHeight + charHeight;
lastX = ImageSizes.marginLeft + backgroundPadding.left + charWidth + lineNumberWidth;
Expand Down

0 comments on commit a5c57aa

Please sign in to comment.