前一陣子看到了一個叫做Brat Text Generator的工具。這個工具讓使用者可以創造出像 Charli XCX 的《BRAT》專輯那種模糊字體搭配綠色背景的封面圖。
我試玩了幾個類似的工具後,做出了一個改良的版本。
模組 | 技術 |
---|---|
前端框架 | Next.js (App Router) |
UI 工具 | Tailwind CSS + DaisyUI |
畫布渲染 | HTML Canvas API |
匯出圖片 | html-to-image |
狀態管理 | useState + useRef |
const canvasRef = useRef<HTMLCanvasElement>(null);
const drawImage = ({
text,
fontSize = 72,
textAlign = 'center',
bgColor = '#00ff00',
textColor = '#ffffff',
width = 1080,
height = 1080
}) => {
const canvas = canvasRef.current;
if (!canvas) return;
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, width, height);
ctx.font = `bold ${fontSize}px 'BratFont', sans-serif`;
ctx.fillStyle = textColor;
ctx.textAlign = textAlign as CanvasTextAlign;
ctx.textBaseline = 'middle';
const lines = text.split('\n');
const lineHeight = fontSize * 1.2;
const startY = height / 2 - ((lines.length - 1) * lineHeight) / 2;
lines.forEach((line, i) => {
const y = startY + i * lineHeight;
ctx.fillText(line, width / 2, y);
});
};
複製
編輯
const downloadImage = () => {
const canvas = canvasRef.current;
if (!canvas) return;
const link = document.createElement('a');
link.download = 'brat-image.png';
link.href = canvas.toDataURL('image/png');
link.click();
};
<input type="color" v-model="bgColor" />
<input type="color" v-model="textColor" />
<input type="range" min="24" max="128" v-model="fontSize" />
<select v-model="textAlign">
<option value="left">靠左</option>
<option value="center">置中</option>
<option value="right">靠右</option>
</select>
const themes = {
classic: {
bgColor: '#00FF00',
textColor: '#FFFFFF'
},
cyber: {
bgColor: '#0000FF',
textColor: '#FF0000'
},
darkmode: {
bgColor: '#000000',
textColor: '#33FF33'
}
};
整體來說,這是一個輕量但可玩性極高的小工具,也讓我學習到如何使用 Canvas 動態渲染、整合 Tailwind UI 以及製作即時圖片匯出功能。未來可能加入更多主題模板或分享功能,歡迎大家玩玩看。