Skip to content

Commit

Permalink
refactor: use TextMetrics for font size if supported
Browse files Browse the repository at this point in the history
  • Loading branch information
weizhenye committed Aug 25, 2024
1 parent 0256425 commit d3a0805
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
8 changes: 6 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,9 @@ export default class ASS {
},
}));

container.append($fixFontSize);
if ($fixFontSize) {
container.append($fixFontSize);
}

const { box } = this.#store;
box.className = 'ASS-box';
Expand Down Expand Up @@ -168,7 +170,9 @@ export default class ASS {
video.removeEventListener('waiting', this.#pause);
video.removeEventListener('seeking', this.#seek);

$fixFontSize.remove();
if ($fixFontSize) {
$fixFontSize.remove();
}
box.remove();
observer.unobserve(this.#store.video);

Expand Down
26 changes: 19 additions & 7 deletions src/renderer/font-size.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,33 @@
// https://github.com/weizhenye/ASS/wiki/Font-Size-in-ASS

const useTextMetrics = 'fontBoundingBoxAscent' in TextMetrics.prototype;

// It seems max line-height is 1200px in Firefox.
const isFirefox = navigator.userAgent.toLowerCase().includes('firefox');
const unitsPerEm = isFirefox ? 512 : 2048;
const unitsPerEm = !useTextMetrics && isFirefox ? 512 : 2048;
const lineSpacing = Object.create(null);

export const $fixFontSize = document.createElement('div');
$fixFontSize.className = 'ASS-fix-font-size';
$fixFontSize.style.fontSize = `${unitsPerEm}px`;
const ctx = document.createElement('canvas').getContext('2d');

const $div = document.createElement('div');
$div.className = 'ASS-fix-font-size';
$div.style.fontSize = `${unitsPerEm}px`;
const $span = document.createElement('span');
$span.textContent = '0';
$fixFontSize.append($span);
$div.append($span);

export const $fixFontSize = useTextMetrics ? null : $div;

export function getRealFontSize(fn, fs) {
if (!lineSpacing[fn]) {
$span.style.fontFamily = fn;
lineSpacing[fn] = $span.clientHeight;
if (useTextMetrics) {
ctx.font = `${unitsPerEm}px "${fn}"`;
const tm = ctx.measureText('');
lineSpacing[fn] = tm.fontBoundingBoxAscent + tm.fontBoundingBoxDescent;
} else {
$span.style.fontFamily = `"${fn}"`;
lineSpacing[fn] = $span.clientHeight;
}
}
return fs * unitsPerEm / lineSpacing[fn];
}

0 comments on commit d3a0805

Please sign in to comment.