icy3dw/src/client/object/canvas-utils.ts

49 lines
1.4 KiB
TypeScript

import { CanvasTexture, LinearFilter, ClampToEdgeWrapping } from 'three';
export class CanvasUtils {
public createTextCanvas(
text: string,
bold = true,
fontSize = 16,
padding = 4,
): { texture: CanvasTexture; width: number; height: number } {
const ctx = document.createElement('canvas').getContext('2d');
const font = `${fontSize}px${bold ? ' bold' : ''} sans`;
// Measure the text bounds
ctx.font = font;
const measure = ctx.measureText(text);
const width = measure.width + padding * 2;
const height = fontSize + padding * 2;
// Resize canvas
ctx.canvas.width = width;
ctx.canvas.height = height;
// Set text parameters
ctx.font = font;
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
// Draw background
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, width, height);
// Scale the text to fit within the canvas
const scaleFactor = Math.min(1, width / measure.width);
ctx.translate(width / 2 - padding, height / 2 - padding);
ctx.scale(scaleFactor, 1);
ctx.fillStyle = '#000';
ctx.fillText(text, padding, padding);
// Create texture with appropriate flags
const texture = new CanvasTexture(ctx.canvas);
texture.minFilter = LinearFilter;
texture.wrapS = ClampToEdgeWrapping;
texture.wrapT = ClampToEdgeWrapping;
return { texture, width: width, height: height };
}
}