利用 Canvas 繪製方塊,三步驟即可實現像素風頭像生成器:解決像素點座標、建立左右對稱關係、循環隨機繪製。支援自訂畫布大小、筆刷大小、上一步復原、Base64 匯出。
// 取得對稱點 X 座標
function getSymmetry(x, canvasWidth, penSize) {
return canvasWidth - x - penSize;
}
// 產生 1~max 的隨機整數
function getRandomInt(max) {
return Math.floor(Math.random() * max) + 1;
}
// 產生能被 penSize 整除的隨機座標(避免半個像素)
function getRandomGridPos(max, penSize) {
let pos;
do {
pos = Math.floor(Math.random() * max);
} while (pos % penSize !== 0);
return pos;
}
const canvas = document.getElementById('avatarCanvas');
const ctx = canvas.getContext('2d');
const canvasSize = 200; // 可自訂
const penSize = 10; // 像素塊大小,可自訂
let history = []; // 歷史紀錄支援復原
function generateAvatar() {
ctx.clearRect(0, 0, canvasSize, canvasSize);
ctx.fillStyle = randomColor(); // 隨機顏色或固定調色盤
const halfWidth = canvasSize / 2;
const maxBlocksPerRow = Math.floor(halfWidth / penSize);
for (let y = 0; y <= canvasSize; y += penSize) {
const blocksThisRow = getRandomInt(maxBlocksPerRow);
for (let i = 0; i < blocksThisRow; i++) {
const x1 = getRandomGridPos(halfWidth, penSize);
const x2 = getSymmetry(x1, canvasSize, penSize);
ctx.fillRect(x1, y, penSize, penSize);
ctx.fillRect(x2, y, penSize, penSize);
}
}
saveState();
}
function saveState() {
history.push(canvas.toDataURL());
if (history.length > 20) history.shift(); // 限制歷史長度
}
function undo() {
if (history.length > 1) {
history.pop(); // 移除當前
const prev = history[history.length - 1];
const img = new Image();
img.onload = () => ctx.drawImage(img, 0, 0);
img.src = prev;
}
}
// 匯出 Base64(支援 IE 右鍵另存)
function exportBase64() {
return canvas.toDataURL('image/png');
}
<canvas id="avatarCanvas" width="200" height="200" style="border:1px solid #ccc;"></canvas>
<div class="controls">
<button onclick="generateAvatar()">生成新頭像</button>
<button onclick="undo()">上一步 (Ctrl+Z)</button>
<button onclick="downloadAvatar()">下載 PNG</button>
<label>畫布大小: <input type="number" id="sizeInput" value="200" min="50" max="500"></label>
<label>像素大小: <input type="number" id="penInput" value="10" min="1" max="50"></label>
</div>
<img id="exportPreview" style="display:none;max-width:300px;">
短短百行代碼,展現 Canvas 像素級繪製的無限創意可能。