paFont Usage
paFont는 OpenType 폰트를 읽어:
- canvas 문단 텍스트로 그리거나
- polygon / region / point geometry로 변환하는 라이브러리입니다.
기본 흐름
1. 폰트 로드
import paFont from "./src/paFont.js";
const font = await paFont.load("/assets/font.otf");
모듈 상대 경로를 쓰고 싶으면:
const font = await paFont.load("./font.otf", {
base: import.meta.url,
});
빠른 예시
1. 텍스트를 geometry로 만들기
const shape = font.text("안녕", {
x: 0,
y: 200,
size: 160,
flatten: 1,
});
const regions = shape.toRegions();
const points = shape.toPoints({ step: 8 });
2. 문단을 canvas에 그리고, 필요하면 geometry로 바꾸기
const paragraph = font.paragraph("캔버스에서 자동 줄바꿈되는 문단입니다.", {
x: 40,
y: 80,
width: 420,
size: 32,
fontFamily: "MyFont",
fontWeight: 400,
lineHeight: 1.4,
align: "left",
engine: "pretext",
});
paragraph.drawText(ctx, {
fillStyle: "#111",
});
const shape = paragraph.toShape();
const regions = paragraph.toRegions({ step: 6, openWidth: 1 });
Font API
paFont.load(source, options?)
폰트를 로드합니다.
source:string | URL | ArrayBuffer | ArrayBufferViewoptions.base: 모듈 기준 상대 경로 해석용
font.text(value, options?)
문자열 전체를 PAShape로 만듭니다.
주요 옵션:
x,y: baseline 시작 위치size: 글자 크기flatten: 곡선 평탄화 허용 오차kerning,letterSpacing,trackingscript,language,features
font.glyph(value, options?)
한 글자만 PAShape로 만듭니다.
font.metrics(value, options?)
텍스트 폭과 bounding box만 빠르게 계산합니다.
const metrics = font.metrics("안녕", { size: 120 });
console.log(metrics.width, metrics.bbox);
font.paragraph(value, options)
문단 레이아웃 객체 paParagraph를 만듭니다.
주요 옵션:
width: 필수, 문단 폭x,y,sizelineHeight:1.4같은 배수 또는 절대 pxalign:left | center | right | justifywhiteSpace:normal | pre-wrap | nowrapoverflowWrap:normal | break-word | anywherefontFamily,fontWeight,fontStyle,fontengine:pretext | nativemaxLines,ellipsis
paParagraph API
font.paragraph()는 paParagraph를 반환합니다.
주요 속성:
paragraph.textparagraph.linesparagraph.metricsparagraph.options
주요 메서드:
paragraph.relayout(next?)
폭이나 정렬이 바뀌었을 때 문단을 다시 레이아웃합니다.
const mobile = paragraph.relayout({ width: 280 });
paragraph.drawText(ctx, options?)
현재 문단 레이아웃을 canvas 텍스트로 그립니다.
paragraph.drawText(ctx, {
fillStyle: "#111",
});
옵션:
fillStylestrokeStylefillstroke
paragraph.toShape(options?)
문단 전체를 하나의 PAShape로 변환합니다.
const shape = paragraph.toShape({
layout: "current",
step: 6,
openWidth: 1,
});
paragraph.toRegions(options?)
문단 전체를 plain region 데이터로 반환합니다.
paragraph.toPoints(options?)
문단 전체를 점 샘플로 반환합니다.
공통 옵션:
layout:current | pretext | nativestepopenWidthincludeHoles(toPoints()전용)
layout 의미:
current: 현재 문단 줄바꿈 그대로 사용pretext:pretext기준으로 다시 줄 계산native:opentype.js측정 기준으로 다시 줄 계산
PAShape API
font.text()와 font.glyph()는 PAShape를 반환합니다.
주요 속성:
shape.textshape.bboxshape.metricsshape.polygons
주요 메서드:
shape.glyphs()
문장을 글자별 PAShape[]로 나눕니다.
shape.toShape({ step, openWidth })
변형된 새 PAShape를 반환합니다.
step: polygon 재샘플링 간격openWidth: hole을 slit처럼 열기 위한 폭
shape.toRegions({ step, openWidth })
최종 polygon 데이터를 반환합니다.
반환 형태:
[
{
outer: [[x, y], ...],
holes: [
[[x, y], ...],
],
bbox: { x, y, w, h },
},
];
shape.toPoints({ step, openWidth, includeHoles })
경계를 일정 간격의 점들로 샘플링합니다.
shape.hit(x, y) / shape.contains(x, y)
도형 hit test를 합니다.
언제 무엇을 쓰나
- 편집/후처리를 계속할 거면
toShape() - 정확한 polygon 데이터가 필요하면
toRegions() - 점 기반 효과나 입자용이면
toPoints() - 문단을 화면에 바로 그리고 싶으면
paragraph.drawText(ctx) - 같은 문단을 geometry로 쓰고 싶으면
paragraph.toShape()
주의
paragraph.drawText()는 canvas 텍스트 렌더링입니다.fontFamily또는font는 브라우저에 실제 등록된 폰트와 맞아야 합니다.step,openWidth는 모두 절대 좌표 단위입니다.