Skip to content

Commit

Permalink
Fix the issue of time consumption when reading invisible characters o…
Browse files Browse the repository at this point in the history
…n the web platform (#296)
  • Loading branch information
Hparty authored Nov 1, 2024
1 parent 976b3d8 commit ccd0ec4
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions web/src/core/scaler-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type {Rect} from '../types';
export class ScalerContext {
public static canvas: HTMLCanvasElement | OffscreenCanvas;
public static context: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
private static hasMeasureBoundsAPI: boolean | undefined = undefined;

public static setCanvas(canvas: HTMLCanvasElement | OffscreenCanvas) {
ScalerContext.canvas = canvas;
Expand Down Expand Up @@ -54,6 +55,14 @@ export class ScalerContext {
return emojiRegExp.test(text);
}

private static measureDirectly(ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D): boolean {
if (ScalerContext.hasMeasureBoundsAPI === undefined) {
const metrics = ctx.measureText('x');
ScalerContext.hasMeasureBoundsAPI = metrics && metrics.actualBoundingBoxAscent > 0;
}
return ScalerContext.hasMeasureBoundsAPI;
}

private readonly fontName: string;
private readonly fontStyle: string;
private readonly size: number;
Expand Down Expand Up @@ -157,9 +166,8 @@ export class ScalerContext {
}

private measureText(ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D, text: string): TextMetrics {
const metrics = ctx.measureText(text);
if (metrics && (metrics.actualBoundingBoxAscent > 0 || metrics.width === 0)) {
return metrics;
if (ScalerContext.measureDirectly(ctx)) {
return ctx.measureText(text);
}
ctx.canvas.width = this.size * 1.5;
ctx.canvas.height = this.size * 1.5;
Expand Down Expand Up @@ -192,4 +200,5 @@ export class ScalerContext {
width: fontMeasure.right - fontMeasure.left,
};
}

}

0 comments on commit ccd0ec4

Please sign in to comment.