Last updated
Converting Code to Images
Converting code to images is useful for sharing on platforms that don't support code formatting, creating documentation screenshots, and generating social media content. The process involves syntax highlighting the code, rendering it in a styled HTML container, and capturing it as a PNG or SVG image.
Approach: Canvas Rendering
// Using dom-to-image library
import domtoimage from 'dom-to-image';
async function codeToImage(codeElement, options = {}) {
const defaults = {
scale: 2, // 2x for retina
bgcolor: '#1e1e2e', // dark background
style: {
padding: '24px',
borderRadius: '12px'
}
};
const config = { ...defaults, ...options };
const blob = await domtoimage.toBlob(codeElement, config);
return URL.createObjectURL(blob);
}
// Download the image
async function downloadCodeImage(codeEl, filename = 'code.png') {
const url = await codeToImage(codeEl);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
SVG-Based Approach
For scalable output, render code as SVG using a foreign object element. This preserves text sharpness at any zoom level and produces smaller files than PNG for text-heavy content. The SVG can then be converted to PNG at any resolution using the canvas approach described above.