DIV CSS 佈局教程網

用 JavaScript 畫圖:從 Canvas API 到自製 2D 繪圖函式集
編輯:關於JavaScript     

早期想在網頁上畫圖,只能靠一張張圖片拼湊,或用 Flash、VML 這類外掛與私有技術。Canvas 的出現改變了這件事:瀏覽器直接提供一塊可繪製的畫布,任何線條、色塊、文字、甚至逐像素的影像處理,都能用 JavaScript 即時完成。本文說明 Canvas 的核心用法,並示範如何把它包成一套好重複使用的 2D 繪圖函式集。

一、取得畫布與繪圖情境

Canvas 只是一塊空白區域,真正的繪圖能力來自 context 物件:

<canvas id="stage" width="600" height="400"></canvas>

const canvas = document.getElementById('stage');
const ctx = canvas.getContext('2d');

所有後續的線條、填色、文字都透過 ctx 下達。若需要像素級操作,同一塊畫布也能改用 getContext('webgl') 或 '2d' 搭配 getImageData 處理。

二、基本繪圖指令

  • 矩形:fillRect(x, y, w, h) 填色、strokeRect 描邊、clearRect 清空區域。
  • 路徑:beginPath() 開始、moveTo / lineTo 連線、arc 畫圓弧、closePath 閉合,最後 fill() 或 stroke() 上色。
  • 文字:fillText 與 strokeText,字型、大小、對齊由 font、textAlign、textBaseline 控制。
  • 樣式:fillStyle、strokeStyle、lineWidth、lineCap、lineJoin、globalAlpha、setLineDash。
  • 座標變換:save() / restore() 搭配 translate、rotate、scale,做出相對座標繪圖與動畫所需的旋轉縮放。

三、把常用動作包成函式集

原始 API 冗長且容易寫錯狀態,實務上會包一層薄薄的工具函式,讓呼叫端只關心「畫什麼」:

const Draw = {
  rect(x, y, w, h, fill, stroke) {
    if (fill) { ctx.fillStyle = fill; ctx.fillRect(x, y, w, h); }
    if (stroke) { ctx.strokeStyle = stroke; ctx.strokeRect(x, y, w, h); }
  },

  circle(cx, cy, r, fill, stroke) {
    ctx.beginPath();
    ctx.arc(cx, cy, r, 0, Math.PI * 2);
    fill && (ctx.fillStyle = fill, ctx.fill());
    stroke && (ctx.strokeStyle = stroke, ctx.stroke());
  },

  line(x1, y1, x2, y2, color, width = 1) {
    ctx.beginPath();
    ctx.strokeStyle = color;
    ctx.lineWidth = width;
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();
  },

  text(str, x, y, font = '16px sans-serif', color = '#000') {
    ctx.font = font;
    ctx.fillStyle = color;
    ctx.fillText(str, x, y);
  },

  clear() { ctx.clearRect(0, 0, canvas.width, canvas.height); }
};

Draw.rect(20, 20, 120, 80, '#4a90d9');
Draw.circle(300, 200, 60, null, '#e8503a');
Draw.line(0, 380, 600, 380, '#333', 2);
Draw.text('Hello Canvas', 20, 340, 'bold 20px sans-serif', '#222');

四、高解析度顯示的關鍵:devicePixelRatio

直接畫在 canvas 上,在 Retina 等高 DPI 螢幕會顯得模糊,因為一個 CSS 像素被填成一個實際像素。做法是放大實際解析度,再用 CSS 縮回原本尺寸,並同步縮放座標系統:

const dpr = window.devicePixelRatio || 1;
const cssW = 600, cssH = 400;

canvas.width = cssW * dpr;
canvas.height = cssH * dpr;
canvas.style.width = cssW + 'px';
canvas.style.height = cssH + 'px';
ctx.scale(dpr, dpr);   // 之後一律用 CSS 像素座標思考

五、讓畫面動起來

Canvas 本身沒有動畫概念,每次更新都要重畫。用 requestAnimationFrame 讓瀏覽器在下一個刷新週期呼叫你的繪製函式,比 setInterval 更順 also 更省電:

let angle = 0;
function loop() {
  Draw.clear();
  Draw.rect(0, 0, 600, 400, '#fafafa');

  ctx.save();
  ctx.translate(300, 200);
  ctx.rotate(angle);
  Draw.rect(-50, -20, 100, 40, '#4a90d9');
  ctx.restore();

  angle += 0.02;
  requestAnimationFrame(loop);
}
requestAnimationFrame(loop);

六、Canvas 還是 SVG?

Canvas 是「像素導向」,適合大量圖形、遊戲、影像處理、資料視覺化的密集繪製,但畫好的內容不會留在 DOM 裡,無障礙與事件命中需要自己處理。SVG 是「物件導向」,每個圖形都是 DOM 節點,能直接用 CSS 設定樣式、能被搜尋引擎與螢幕閱讀器理解,適合圖示、圖表與需要互動的向量圖。選錯工具比寫錯程式更耗時間。

結語

Canvas 的學習曲線在於它「什麼都不幫你做」——沒有版面、沒有事件、沒有無障礙樹。但也正因如此,只要願意多包一層自己的函式集,就能得到極高的自由度與效能。先熟練路徑、狀態與座標變換這三件事,其餘都是排列組合。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved