Text to image converter with image size, font size selection
Text to Image Converter
// Set canvas background color ctx.fillStyle = bgColor; ctx.fillRect(0, 0, canvas.width, canvas.height);
// Set text properties ctx.fillStyle = textColor; ctx.font = `bold ${fontSize}px Arial`; ctx.textAlign = "center"; ctx.textBaseline = "middle";
// Function to wrap text function wrapText(context, text, x, y, maxWidth, lineHeight) { const words = text.split(' '); let line = ''; let lines = []; for (let n = 0; n < words.length; n++) { const testLine = line + words[n] + ' '; const metrics = context.measureText(testLine); const testWidth = metrics.width; if (testWidth > maxWidth && n > 0) { lines.push(line); line = words[n] + ' '; } else { line = testLine; } } lines.push(line);
const totalHeight = lines.length * lineHeight; const startY = y - (totalHeight / 2);
for (let i = 0; i < lines.length; i++) {
context.fillText(lines[i], x, startY + (i * lineHeight));
}
}
// Wrap and draw text in the center
const maxWidth = canvas.width - 40; // padding of 20px on each side
const lineHeight = fontSize + 10;
const x = canvas.width / 2; // center horizontally
const y = canvas.height / 2; // center vertically
wrapText(ctx, text, x, y, maxWidth, lineHeight);
// Convert canvas to data URL
const dataUrl = canvas.toDataURL('image/jpeg');
// Create an image element
const img = document.createElement('img');
img.src = dataUrl;
img.alt = 'Generated Image';
// Create a download link
const link = document.createElement('a');
link.href = dataUrl;
link.download = 'text-image.jpg';
link.textContent = 'Download Image';
link.style.display = 'block';
link.style.marginTop = '10px';
// Clear previous images and links, then display the new image and download link
const imageContainer = document.getElementById('imageContainer');
imageContainer.innerHTML = '';
imageContainer.appendChild(img);
imageContainer.appendChild(link);
}
Updated Daily – Latest Govt Jobs & Education News
