想要在網頁上做出溫度感?Canvas 的粒子系統是最經典的起點。這個效果的做法是:產生大量帶有半徑、速度與生命週期的小粒子,每一格畫面為它們畫上放射狀漸層,再讓整批粒子往上升、變小、消失、重生——火焰的跳動感就出現了。加上滑鼠座標的追蹤,火焰便會黏著游標移動。
source-over 把畫布填黑,再切換成 lighter(加法混合),讓粒子重疊處自然變亮,這是火焰感的關鍵。createRadialGradient 畫出中心不透明、外緣全透明的圓,邊緣才不會有硬邦邦的輪廓。把以下內容存成 .html 檔直接開啟即可看到火焰跟著游標移動。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<title>HTML5 Canvas 火焰效果</title>
<style type="text/css">
body { margin: 0; padding: 0; overflow: hidden; }
#flame { display: block; }
</style>
</head>
<body>
<canvas id="flame"></canvas>
<script>
window.onload = function () {
var canvas = document.getElementById('flame');
var ctx = canvas.getContext('2d');
var W = window.innerWidth, H = window.innerHeight;
canvas.width = W;
canvas.height = H;
var particles = [];
var mouse = {};
var PARTICLE_COUNT = 100;
// 粒子:位置、速度、半徑、壽命、顏色
function Particle() {
this.speed = { x: -2.5 + Math.random() * 5, y: -15 + Math.random() * 10 };
// 有滑鼠座標就從游標產生,否則從畫面中央
if (mouse.x && mouse.y) {
this.location = { x: mouse.x, y: mouse.y };
} else {
this.location = { x: W / 2, y: H / 2 };
}
this.radius = 10 + Math.random() * 20; // 半徑 10~30
this.life = 20 + Math.random() * 10; // 壽命 20~30 格
this.remaining_life = this.life;
this.r = Math.round(Math.random() * 255);
this.g = Math.round(Math.random() * 255);
this.b = Math.round(Math.random() * 255);
}
for (var i = 0; i < PARTICLE_COUNT; i++) {
particles.push(new Particle());
}
canvas.addEventListener('mousemove', function (e) {
mouse.x = e.pageX;
mouse.y = e.pageY;
}, false);
function draw() {
// 1. 清成黑底
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, W, H);
// 2. 加法混合,重疊處更亮
ctx.globalCompositeOperation = 'lighter';
for (var i = 0; i < particles.length; i++) {
var p = particles[i];
p.opacity = Math.round(p.remaining_life / p.life * 100) / 100;
var grad = ctx.createRadialGradient(
p.location.x, p.location.y, 0,
p.location.x, p.location.y, p.radius
);
grad.addColorStop(0, 'rgba(' + p.r + ',' + p.g + ',' + p.b + ',' + p.opacity + ')');
grad.addColorStop(0.5, 'rgba(' + p.r + ',' + p.g + ',' + p.b + ',' + p.opacity + ')');
grad.addColorStop(1, 'rgba(' + p.r + ',' + p.g + ',' + p.b + ',0)');
ctx.fillStyle = grad;
ctx.beginPath();
ctx.arc(p.location.x, p.location.y, p.radius, Math.PI * 2, false);
ctx.fill();
// 3. 老化:壽命與半徑遞減,並依速度位移
p.remaining_life--;
p.radius--;
p.location.x += p.speed.x;
p.location.y += p.speed.y;
// 4. 消亡即重生
if (p.remaining_life < 0 || p.radius < 0) {
particles[i] = new Particle();
}
}
}
setInterval(draw, 86);
};
</script>
</body>
</html>
把 setInterval 換成 requestAnimationFrame,畫面會順得多,也能配合 document.hidden 在切到別的分頁時自動暫停,省下 CPU。另外,觸控裝置沒有 mousemove,記得補上 touchmove 事件並搭配 e.touches[0].pageX/pageY;若想讓火焰更「火紅」,可把色相鎖在紅橙黃區間(例如 r=255、g 介於 80~200),而不是全彩隨機。