萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 Canvas 打造像素風頭像生成器:三步驟核心邏輯完整實作

利用 Canvas 繪製方塊,三步驟即可實現像素風頭像生成器:解決像素點座標、建立左右對稱關係、循環隨機繪製。支援自訂畫布大小、筆刷大小、上一步復原、Base64 匯出。

核心三步驟

  1. 像素點座標:畫布網格化,每格為一像素單位
  2. 對稱關係:左側繪製,右側鏡像對稱
  3. 隨機循環繪製:每行隨機決定繪製幾個像素點

關鍵函式實作

// 取得對稱點 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');
}

完整 HTML 整合

<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;">

進階擴充想法

  • 調色盤系統:預設多組配色方案(復古、莫蘭迪、賽博龐克)
  • 種子值分享:將隨機種子編碼於 URL,分享連結即可完美復現
  • 動畫生成過程:`requestAnimationFrame` 逐行繪製動畫
  • Web Worker 運算:大畫布時移至背景執行緒避免阻塞主執行緒
  • NFT 元數據:輸出 ERC-721 兼容的 attributes JSON

短短百行代碼,展現 Canvas 像素級繪製的無限創意可能。

copyright © 萬盛學電腦網 all rights reserved