export interface TextImageOptions { font?: string; textAlign?: CanvasTextAlign; width?: number; height?: number; } function createTextImage( text: string, textColor: string, backgroundColor: string | false, options: TextImageOptions = {} ): HTMLImageElement { const { height, width, font, textAlign } = { ...{ font: '30px Arial', textAlign:'center', width: 400, height:200 }, ...options, } // Create a canvas element const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); if (!context) { throw new Error('Failed to get canvas context'); } // Set canvas dimensions canvas.width = width; canvas.height = height; // Set background color if (backgroundColor) { context.fillStyle = backgroundColor; context.fillRect(0, 0, width, height); } else { // Transparent background context.clearRect(0, 0, width, height); } // Set text properties context.fillStyle = textColor; context.font = font; context.textAlign = textAlign as CanvasTextAlign; context.textBaseline = 'middle'; // Split text by \n and draw each line const lines = text.split('\n'); const lineHeight = parseInt(font, 10) * 1.2; // Adjust line height as needed lines.forEach((line, index) => { context.fillText(line, width / 2, (height / 2) - ((lines.length - 1) * lineHeight / 2) + (index * lineHeight)); }); // Create an image element const image = new Image(); image.src = canvas.toDataURL('image/png'); return image; } export default createTextImage;