textRenderer.tsx 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import {FlamegraphTheme} from '../flamegraph/flamegraphTheme';
  2. import {getContext, resizeCanvasToDisplaySize} from '../gl/utils';
  3. const TEST_STRING = 'Who knows if this changed, font-display: swap wont tell me';
  4. abstract class TextRenderer {
  5. canvas: HTMLCanvasElement;
  6. theme: FlamegraphTheme;
  7. context: CanvasRenderingContext2D;
  8. textCache: Record<string, TextMetrics>;
  9. constructor(canvas: HTMLCanvasElement, theme: FlamegraphTheme) {
  10. this.canvas = canvas;
  11. this.theme = theme;
  12. this.textCache = {};
  13. this.context = getContext(canvas, '2d');
  14. resizeCanvasToDisplaySize(canvas);
  15. }
  16. measureAndCacheText(text: string): TextMetrics {
  17. if (this.textCache[text]) {
  18. return this.textCache[text];
  19. }
  20. this.textCache[text] = this.context.measureText(text);
  21. return this.textCache[text];
  22. }
  23. maybeInvalidateCache(): void {
  24. if (this.textCache[TEST_STRING] === undefined) {
  25. this.measureAndCacheText(TEST_STRING);
  26. return;
  27. }
  28. const newMeasuredSize = this.context.measureText(TEST_STRING);
  29. if (newMeasuredSize !== this.textCache[TEST_STRING]) {
  30. this.textCache = {[TEST_STRING]: newMeasuredSize};
  31. }
  32. }
  33. }
  34. export {TextRenderer};