桌面瀏覽器曾因 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>
pointer: coarse 偵測觸控裝置,prefers-reduced-motion 尊重無障礙偏好Canvas 與 CSS3 結合,可在行動瀏覽器構建媲美原生 App 的視覺體驗。