| 1 | /** |
| 2 | * Minimal canvas2d→WebGL text helper for frameworkv3 (GL) scenes. |
| 3 | * Scene.context is now a WebGLRenderingContext, so fillText/measureText no longer work. |
| 4 | * We rasterize once to a 2D canvas and draw via the framework `image` sprite path. |
| 5 | */ |
| 6 | class GlText |
| 7 | { |
| 8 | static _cache = {}; |
| 9 | |
| 10 | /** |
| 11 | * @param {Scene} scene |
| 12 | * @param {string} text |
| 13 | * @param {number} x center x in scene space |
| 14 | * @param {number} y baseline-ish center y in scene space |
| 15 | * @param {{ font?: string, fill?: string, maxWidth?: number }} [opts] |
| 16 | */ |
| 17 | static drawCentered (scene, text, x, y, opts) |
| 18 | { |
| 19 | opts = opts || {}; |
| 20 | const font = opts.font || "20px Monospace"; |
| 21 | const fill = opts.fill || "black"; |
| 22 | const key = font + "|" + fill + "|" + text; |
| 23 | let sprite = GlText._cache[key]; |
| 24 | |
| 25 | if (!sprite) |
| 26 | { |
| 27 | const measure = document.createElement("canvas"); |
| 28 | const mctx = measure.getContext("2d"); |
| 29 | mctx.font = font; |
| 30 | const metrics = mctx.measureText(text); |
| 31 | const w = Math.max(1, Math.ceil(metrics.width) + 4); |
| 32 | const h = 28; |
| 33 | |
| 34 | const c = document.createElement("canvas"); |
| 35 | c.width = w; |
| 36 | c.height = h; |
| 37 | const ctx = c.getContext("2d"); |
| 38 | ctx.font = font; |
| 39 | ctx.fillStyle = fill; |
| 40 | ctx.textBaseline = "middle"; |
| 41 | ctx.textAlign = "left"; |
| 42 | ctx.fillText(text, 2, h / 2); |
| 43 | |
| 44 | sprite = new image(c, 1, 1); |
| 45 | GlText._cache[key] = sprite; |
| 46 | } |
| 47 | |
| 48 | const dw = opts.maxWidth ? Math.min(sprite.width, opts.maxWidth) : sprite.width; |
| 49 | const dh = sprite.height; |
| 50 | sprite.draw(scene, x, y, dw, dh, 0, 0, 0, 1, 0); |
| 51 | } |
| 52 | } |