(
name: string,
color: string,
maxTextWidth = TEXTURE_MAX_TEXT_WIDTH,
)
| 109 | } |
| 110 | |
| 111 | function createLabelTexture( |
| 112 | name: string, |
| 113 | color: string, |
| 114 | maxTextWidth = TEXTURE_MAX_TEXT_WIDTH, |
| 115 | ): LabelTexture | null { |
| 116 | const canvas = document.createElement('canvas'); |
| 117 | const ctx = canvas.getContext('2d'); |
| 118 | if (!ctx) { |
| 119 | return null; |
| 120 | } |
| 121 | |
| 122 | ctx.font = TEXTURE_FONT; |
| 123 | const text = fitText(ctx, name, maxTextWidth); |
| 124 | const textWidth = Math.ceil(ctx.measureText(text).width); |
| 125 | const logicalWidth = Math.max( |
| 126 | 1, |
| 127 | textWidth + TEXTURE_PADDING_X * 2 + TEXTURE_STROKE_WIDTH * 2, |
| 128 | ); |
| 129 | const logicalHeight = |
| 130 | TEXTURE_FONT_SIZE + TEXTURE_PADDING_Y * 2 + TEXTURE_STROKE_WIDTH * 2; |
| 131 | const pixelRatio = |
| 132 | typeof window === 'undefined' |
| 133 | ? 1 |
| 134 | : Math.min(window.devicePixelRatio || 1, 2); |
| 135 | |
| 136 | canvas.width = Math.ceil(logicalWidth * pixelRatio); |
| 137 | canvas.height = Math.ceil(logicalHeight * pixelRatio); |
| 138 | canvas.style.width = `${logicalWidth}px`; |
| 139 | canvas.style.height = `${logicalHeight}px`; |
| 140 | |
| 141 | ctx.scale(pixelRatio, pixelRatio); |
| 142 | ctx.font = TEXTURE_FONT; |
| 143 | ctx.textAlign = 'center'; |
| 144 | ctx.textBaseline = 'middle'; |
| 145 | ctx.lineJoin = 'round'; |
| 146 | ctx.lineWidth = TEXTURE_STROKE_WIDTH; |
| 147 | ctx.strokeStyle = 'rgba(0, 0, 0, 0.9)'; |
| 148 | ctx.fillStyle = color; |
| 149 | |
| 150 | const x = logicalWidth / 2; |
| 151 | const y = logicalHeight / 2; |
| 152 | ctx.strokeText(text, x, y); |
| 153 | ctx.fillText(text, x, y); |
| 154 | |
| 155 | const texture = new THREE.CanvasTexture(canvas); |
| 156 | texture.colorSpace = THREE.SRGBColorSpace; |
| 157 | texture.minFilter = THREE.LinearFilter; |
| 158 | texture.magFilter = THREE.LinearFilter; |
| 159 | texture.generateMipmaps = false; |
| 160 | texture.needsUpdate = true; |
| 161 | |
| 162 | return { |
| 163 | texture, |
| 164 | width: logicalWidth, |
| 165 | height: logicalHeight, |
| 166 | }; |
| 167 | } |
| 168 |
no test coverage detected