萬盛學電腦網

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

HTML5 移動應用開發實戰(五):Canvas 繪圖與 CSS3 視覺新特性

Canvas:行動端的原生繪圖利器

桌面瀏覽器曾因 IE 不支援 Canvas 而令開發者望之卻步,但行動端 WebKit 內核瀏覽器(iOS Safari、Android Browser、Chrome for Android)早已完整支援並深度優化。Canvas 提供低階繪圖 API:路徑、漸層、文字、幾何變換、像素級操作,適用於圖表、遊戲、影像編輯等場景。

實戰:動態產生年度銷售長條圖

下列程式碼示範在 <canvas> 即時繪製互動式長條圖,支援觸控提示:

<canvas id="chart" width="320" height="240"></canvas>

<script>
const data = [
  {year: '2021', sales: 49},
  {year: '2022', sales: 72},
  {year: '2023', sales: 58},
  {year: '2024', sales: 91}
];

const cvs = document.getElementById('chart');
const ctx = cvs.getContext('2d');
const padding = 40;
const barWidth = 40;
const maxSales = Math.max(...data.map(d => d.sales));

function draw() {
  ctx.clearRect(0, 0, cvs.width, cvs.height);
  // 座標軸
  ctx.strokeStyle = '#999';
  ctx.beginPath();
  ctx.moveTo(padding, padding);
  ctx.lineTo(padding, cvs.height - padding);
  ctx.lineTo(cvs.width - padding, cvs.height - padding);
  ctx.stroke();

  // 長條
  data.forEach((d, i) => {
    const x = padding + 20 + i * (barWidth + 20);
    const barHeight = (d.sales / maxSales) * (cvs.height - 2 * padding);
    const y = cvs.height - padding - barHeight;

    ctx.fillStyle = `hsl(${i * 60}, 70%, 50%)`;
    ctx.fillRect(x, y, barWidth, barHeight);

    // 年份標籤
    ctx.fillStyle = '#333';
    ctx.font = '12px sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText(d.year, x + barWidth/2, cvs.height - padding + 20);
  });
}

draw();

// 觸控互動:顯示數值提示
cvs.addEventListener('touchstart', e => {
  const rect = cvs.getBoundingClientRect();
  const tx = e.touches[0].clientX - rect.left;
  data.forEach((d, i) => {
    const x = padding + 20 + i * (barWidth + 20);
    if (tx > x && tx < x + barWidth) {
      ctx.fillStyle = 'rgba(0,0,0,0.7)';
      ctx.fillRect(x, cvs.height - padding - 30, barWidth, 25);
      ctx.fillStyle = '#fff';
      ctx.fillText(d.sales + ' 萬', x + barWidth/2, cvs.height - padding - 10);
    }
  });
});
</script>

CSS3 視覺增強新特性

  • CSS Gradients:無圖片實現線性/徑向漸層,減少 HTTP 請求
  • CSS Transforms/Transitions/Animations:GPU 加速動畫,效能遠超 JS 幀動畫
  • Flexbox / Grid:現代佈局系統,完美適配多螢幕尺寸
  • Media Queries Level 4:pointer: coarse 偵測觸控裝置,prefers-reduced-motion 尊重無障礙偏好

Canvas 與 CSS3 結合,可在行動瀏覽器構建媲美原生 App 的視覺體驗。

copyright © 萬盛學電腦網 all rights reserved