diff --git a/__test__/regression.spec.ts b/__test__/regression.spec.ts index de0e6aa5..93fed413 100644 --- a/__test__/regression.spec.ts +++ b/__test__/regression.spec.ts @@ -1,10 +1,10 @@ import { promises as fs } from 'fs' +import { join } from 'path' import test from 'ava' -import { createCanvas, loadImage } from '../index' +import { createCanvas, loadImage, GlobalFonts } from '../index' import { snapshotImage } from './image-snapshot' -import { join } from 'path' test('transform-with-state', async (t) => { const canvas = createCanvas(256, 256) @@ -104,3 +104,23 @@ test('global-alpha-should-effect-drawImage', async (t) => { ctx.drawImage(await loadImage(image), 0, 0, 200, 100) await snapshotImage(t, { ctx, canvas }, 'png', 1) }) + +test('draw-text-maxWidth', async (t) => { + GlobalFonts.registerFromPath(join(__dirname, 'fonts', 'iosevka-slab-regular.ttf')) + const canvas = createCanvas(150, 150) + const ctx = canvas.getContext('2d') + const pad = 10 // padding + ctx.textBaseline = 'top' + ctx.font = '50px Iosevka Slab' + + ctx.fillRect(0, 0, canvas.width, canvas.height) + + ctx.fillStyle = 'blue' + ctx.fillRect(pad, pad, canvas.width - pad * 2, canvas.height - pad * 2) + + const maxWidth = canvas.width - pad * 2 + ctx.fillStyle = 'white' + ctx.fillText('Short text', pad, 10, maxWidth) + ctx.fillText(`Very ${'long '.repeat(2)} text`, pad, 80, maxWidth) + await snapshotImage(t, { ctx, canvas }) +}) diff --git a/__test__/snapshots/draw-text-maxWidth.png b/__test__/snapshots/draw-text-maxWidth.png new file mode 100644 index 00000000..b4a45900 Binary files /dev/null and b/__test__/snapshots/draw-text-maxWidth.png differ diff --git a/skia-c/skia_c.cpp b/skia-c/skia_c.cpp index 57f6e1a8..7a602111 100644 --- a/skia-c/skia_c.cpp +++ b/skia-c/skia_c.cpp @@ -511,13 +511,14 @@ extern "C" break; }; auto need_scale = line_width > max_width; + float ratio = need_scale ? max_width / line_width : 1.0; if (need_scale) { CANVAS_CAST->save(); - CANVAS_CAST->scale(max_width / line_width, 1.0); + CANVAS_CAST->scale(ratio, 1.0); } auto paint_y = y + baseline_offset; - paragraph->paint(CANVAS_CAST, paint_x, paint_y); + paragraph->paint(CANVAS_CAST, need_scale ? paint_x / ratio : paint_x, paint_y); if (need_scale) { CANVAS_CAST->restore();