JS表白代码大全:5种炫酷网页特效源码及修改教程
精选5款纯原生JavaScript与Canvas实现的炫酷网页表白特效源码,包含数学爱心粒子、打字机情书交互、3D深邃星空流星、浪漫樱花与恋爱计时器、炫彩烟花光斑。提供完整独立可运行源码、关键参数修改指南及上线避坑方案。
一、网页表白特效实施与自定义落地全流程
许多初学者在获取网页特效源码后,常常因为字符编码不匹配、缺少对应运行环境或定位不到关键变量而导致页面异常。实际上,纯前端特效的修改与落地具有一套非常标准的工作步骤。只要按部就班完成准备、定制、调试与上线四个环节,就能确保网页在电脑与手机端都展现出预期的动态效果。
按照图 1 所示的工作流,整个定制过程分为以下四个具体步骤:
-
建立本地单文件工程:在电脑桌面或工作目录中新建一个文件夹(例如命名为
love-page),在其中创建一个名为index.html的空白文本文件。确保文件头声明<meta charset="UTF-8">,避免在中文操作系统下因编码格式不一致出现文字乱码。 -
定制关键文本与视觉数据:使用系统自带的文本编辑器(或 VS Code、Sublime Text)打开
index.html,定位到文中的配置区域(通常在<script>标签起始处的常量对象中),替换主角姓名、纪念日时间戳、表白信正文以及粒子色彩十六进制值。 -
本地浏览器调试与参数微调:保存修改后,直接双击
index.html,系统默认浏览器会自动打开该页面。通过观察动画的刷新速率、字体排版以及交互反馈,按需微调粒子密度、下落速度或按钮逃逸灵敏度。 - 免费静态托管与手机扫码分享:为了让对方能在手机上随时打开,无需购买域名和服务器,可直接将该 HTML 文件上传至 GitHub Pages、Gitee Pages 或 Vercel 等免费静态网页托管平台,生成唯一的公网 HTTPS 链接和二维码。
二、5种表白特效技术架构与性能矩阵对比
不同视觉特效背后的技术实现路线差异很大。在挑选特效之前,了解其底层的渲染机制有助于根据目标展示设备(如电脑高分辨率大屏还是低功耗手机)作出合理选择。
从渲染机制来看,主要分为两类技术路线:
-
Canvas 2D 逐帧重绘体系:如“数学爱心粒子”和“3D全屏星空”,通过
requestAnimationFrame以每秒 60 次的频率重新绘制成千上万个像素点或微小图形。这种方式能够呈现细腻的物理运动和流体光效,但对移动端 CPU/GPU 的瞬间算力有一定要求,需要合理控制粒子上限。 - DOM 状态与 CSS3 硬件加速体系:如“打字机告白信”与“樱花飘落计时器”,主要利用浏览器的 DOM 树渲染和 GPU 独立的合成图层(Compositing Layer)。其内存占用通常在 10MB 以内,即使在配置较低的老旧智能手机上也能保持平稳运行,非常适合展示文字较多的深情告白信。
三、5款炫酷表白特效源码与逐行修改教程
特效一:经典 Canvas 数学心形粒子聚合爆发特效
该特效基于经典的笛卡尔心形参数方程,由数百个具有微小光晕的高光粒子构成。初次加载时,粒子从全屏随机坐标向心形轨迹聚拢;聚拢后伴随类似心脏跳动的周期性缩放律动;当鼠标移动或手指触摸屏幕时,粒子会受到径向排斥力向外散开,随后平滑弹回原位。
以下为完整的单文件 HTML 源码,可直接复制并保存为 heart.html 运行:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>唯美数学爱心粒子</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { background: #0b0e14; overflow: hidden; display: flex; justify-content: center; align-items: center; height: 100vh; }
canvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
.center-text {
position: absolute;
color: #ffb6c1;
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
font-size: 24px;
font-weight: bold;
letter-spacing: 2px;
text-shadow: 0 0 12px rgba(255, 105, 180, 0.8);
pointer-events: none;
text-align: center;
}
</style>
</head>
<body>
<canvas id="heartCanvas"></canvas>
<div class="center-text" id="centerText">
<span>To My Dearest</span><br>
<span style="font-size: 15px; color: #ffd1dc; opacity: 0.85;">执子之手 · 与子偕老</span>
</div>
<script>
// ===== 自定义配置区域 =====
const CONFIG = {
particleCount: 420, // 粒子总数量(推荐 300 - 600,过大可能卡顿)
heartScale: 14, // 心形基础放大倍数
primaryColor: '#ff4d6d', // 主心形粒子颜色(珊瑚粉)
accentColor: '#ff8fa3', // 边缘光晕颜色
pulseSpeed: 0.04 // 心跳跳动频率
};
const canvas = document.getElementById('heartCanvas');
const ctx = canvas.getContext('2d');
let width, height, dpr;
let particles = [];
let pulseTime = 0;
const mouse = { x: -9999, y: -9999 };
function resize() {
dpr = window.devicePixelRatio || 1;
width = window.innerWidth;
height = window.innerHeight;
canvas.width = width * dpr;
canvas.height = height * dpr;
ctx.scale(dpr, dpr);
}
window.addEventListener('resize', resize);
resize();
// 心形参数方程:x = 16 * sin^3(t), y = -(13*cos(t) - 5*cos(2t) - 2*cos(3t) - cos(4t))
function getHeartPoint(t, scale) {
const x = 16 * Math.pow(Math.sin(t), 3);
const y = -(13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t));
return { x: x * scale, y: y * scale };
}
class Particle {
constructor(t) {
this.t = t;
this.x = (Math.random() - 0.5) * width;
this.y = (Math.random() - 0.5) * height;
this.vx = 0;
this.vy = 0;
this.size = Math.random() * 2 + 1.2;
this.color = Math.random() > 0.3 ? CONFIG.primaryColor : CONFIG.accentColor;
this.alpha = Math.random() * 0.5 + 0.5;
}
update(currentScale) {
const target = getHeartPoint(this.t, currentScale);
const targetX = target.x + (Math.random() - 0.5) * 8;
const targetY = target.y + (Math.random() - 0.5) * 8;
// 弹性恢复力
const dx = targetX - this.x;
const dy = targetY - this.y;
this.vx += dx * 0.05;
this.vy += dy * 0.05;
this.vx *= 0.88; // 摩擦阻尼
this.vy *= 0.88;
// 鼠标排斥互动
const mdx = (this.x + width / 2) - mouse.x;
const mdy = (this.y + height / 2) - mouse.y;
const dist = Math.sqrt(mdx * mdx + mdy * mdy);
if (dist < 90) {
const force = (90 - dist) / 90 * 8;
this.vx += (mdx / dist) * force;
this.vy += (mdy / dist) * force;
}
this.x += this.vx;
this.y += this.vy;
}
draw() {
ctx.save();
ctx.translate(width / 2, height / 2);
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.alpha;
ctx.shadowBlur = 8;
ctx.shadowColor = this.color;
ctx.fill();
ctx.restore();
}
}
// 初始化粒子
for (let i = 0; i < CONFIG.particleCount; i++) {
const t = (i / CONFIG.particleCount) * Math.PI * 2;
particles.push(new Particle(t));
}
// 交互监听
window.addEventListener('mousemove', e => { mouse.x = e.clientX; mouse.y = e.clientY; });
window.addEventListener('touchmove', e => {
if (e.touches.length > 0) {
mouse.x = e.touches[0].clientX;
mouse.y = e.touches[0].clientY;
}
});
window.addEventListener('touchend', () => { mouse.x = -9999; mouse.y = -9999; });
function animate() {
// 产生微弱拖尾背景
ctx.fillStyle = 'rgba(11, 14, 20, 0.25)';
ctx.fillRect(0, 0, width, height);
pulseTime += CONFIG.pulseSpeed;
const heartPulse = CONFIG.heartScale * (1 + 0.12 * Math.sin(pulseTime));
particles.forEach(p => {
p.update(heartPulse);
p.draw();
});
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
1. 文案替换:修改 HTML 中 <div class="center-text"> 内的两行文本即可替换中心展示的名字与誓言。
2. 颜色调配:在 CONFIG 对象中,修改 primaryColor(如改成土豪金 #c5a059 或纯净冰蓝 #00b4d8),粒子与中心发光阴影将同步改变风格。
3. 大小适配:heartScale 控制爱心大小。若在手机端觉得心形偏大,可在移动端检测中将其缩小为 10 ~ 12。
特效二:交互式打字机告白信与“无法拒绝”趣味按钮
打字机效果模拟了纸质信件逐字打出的真实感,右下角带有闪烁的光标。读完全文后,页面下方会渐变显示两个按钮:“好呀”(同意)和“再想想”(拒绝)。当用户的鼠标光标移动到“再想想”上方(或手机手指触碰时),该按钮会以随机坐标迅速“跳跃逃逸”,使用户永远无法点击到拒绝选项,带来轻松幽默的情感互动体验。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>给你的专属情书</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: #fbf7f0;
color: #3e3834;
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.letter-card {
background: #ffffff;
max-width: 620px;
width: 100%;
padding: 36px 32px;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(80, 60, 45, 0.08);
border: 1px solid #ebdcd0;
position: relative;
}
.letter-title {
font-size: 22px;
font-weight: bold;
color: #7a4b37;
margin-bottom: 20px;
border-bottom: 2px dashed #f0ded3;
padding-bottom: 12px;
}
.typewriter-content {
font-size: 16px;
line-height: 1.85;
min-height: 140px;
white-space: pre-wrap;
}
.cursor {
display: inline-block;
width: 2px;
height: 1.1em;
background-color: #7a4b37;
margin-left: 2px;
vertical-align: text-bottom;
animation: blink 0.8s infinite;
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
.action-group {
margin-top: 36px;
display: flex;
gap: 20px;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity 1s ease;
height: 48px;
position: relative;
}
.btn {
padding: 10px 30px;
font-size: 15px;
font-weight: bold;
border-radius: 24px;
border: none;
cursor: pointer;
transition: transform 0.2s;
}
.btn-yes {
background: #c55348;
color: #ffffff;
box-shadow: 0 4px 12px rgba(197, 83, 72, 0.3);
}
.btn-yes:hover { transform: scale(1.05); }
.btn-no {
background: #e8ded8;
color: #665b55;
position: absolute;
right: 120px;
}
</style>
</head>
<body>
<div class="letter-card">
<div class="letter-title">致最特别的你:</div>
<div class="typewriter-content" id="typewriter"></div><span class="cursor" id="cursor"></span>
<div class="action-group" id="actionGroup">
<button class="btn btn-yes" onclick="handleAgree()">好呀 ❤️</button>
<button class="btn btn-no" id="btnNo" onmouseover="dodgeBtn()" onclick="dodgeBtn()">再想想</button>
</div>
</div>
<script>
// ===== 自定义情书正文 =====
const letterText =
"自从相遇的那一天起,平凡的日常好像都染上了明亮的光彩。
" +
"走过四季的街巷,看遍初雪与晴空,最安心的事莫过于身旁有你。
" +
"以后的春夏秋冬、柴米油盐,我也想一直陪你走下去。
" +
"今天,想正式问你一句话:做我女朋友好不好?";
const typeElement = document.getElementById('typewriter');
const cursor = document.getElementById('cursor');
const actionGroup = document.getElementById('actionGroup');
const btnNo = document.getElementById('btnNo');
let charIndex = 0;
const typeSpeed = 55; // 打字间隔毫秒数
function typeWriter() {
if (charIndex < letterText.length) {
typeElement.textContent += letterText.charAt(charIndex);
charIndex++;
setTimeout(typeWriter, typeSpeed);
} else {
cursor.style.display = 'none'; // 打字完成隐藏光标
actionGroup.style.opacity = '1'; // 显示交互按钮
}
}
window.onload = typeWriter;
// 拒绝按钮逃逸逻辑
function dodgeBtn() {
const card = document.querySelector('.letter-card');
const maxX = card.clientWidth - btnNo.clientWidth - 40;
const maxY = card.clientHeight - btnNo.clientHeight - 40;
const randomX = Math.floor(Math.random() * maxX);
const randomY = Math.floor(Math.random() * maxY);
btnNo.style.position = 'absolute';
btnNo.style.left = randomX + 'px';
btnNo.style.top = randomY + 'px';
}
// 点击同意逻辑
function handleAgree() {
alert("太好啦!余生请多指教 ❤️");
}
</script>
</body>
</html>
1. 告白文本:直接编辑 letterText 字符串中的文段内容,用
表示换行。
2. 打字节奏:修改 typeSpeed 的数值,数值越小打字越快(建议保持在 40 到 70 之间)。
3. 成功反馈:在 handleAgree() 中,可将简单的 alert 替换为跳转到一个绚烂的烟花页面,或者弹出一个精美的模态框。
特效三:3D 全屏深邃星空与许愿流星划过特效
星空特效以深色宇宙为背景,生成大量带有视差景深的恒星。近处的星星明亮且相对运动较快,远处的星星闪烁暗淡。系统每隔固定周期从天空随机边缘划过一道带有渐变长尾的流星,中心浮现优雅的发光文本,营造静谧而浪漫的夜空氛围。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>漫天星空与许愿流星</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { background: #05060d; overflow: hidden; height: 100vh; }
canvas { display: block; position: absolute; top: 0; left: 0; }
.star-message {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #ffffff;
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
text-align: center;
pointer-events: none;
z-index: 10;
}
.star-message h1 {
font-size: 26px;
font-weight: 300;
letter-spacing: 4px;
text-shadow: 0 0 16px rgba(186, 218, 255, 0.8);
margin-bottom: 8px;
}
.star-message p {
font-size: 14px;
color: #9cb3d1;
letter-spacing: 2px;
}
</style>
</head>
<body>
<canvas id="space"></canvas>
<div class="star-message">
<h1>山河远阔 · 人间星河</h1>
<p>Every Star Wishes For You</p>
</div>
<script>
const canvas = document.getElementById('space');
const ctx = canvas.getContext('2d');
let w, h;
function resize() {
w = canvas.width = window.innerWidth;
h = canvas.height = window.innerHeight;
}
window.addEventListener('resize', resize);
resize();
// 恒星生成
const stars = [];
const STAR_COUNT = 300;
for (let i = 0; i < STAR_COUNT; i++) {
stars.push({
x: Math.random() * w,
y: Math.random() * h,
radius: Math.random() * 1.4,
alpha: Math.random(),
speed: Math.random() * 0.02 + 0.005
});
}
// 流星数组
const meteors = [];
class Meteor {
constructor() {
this.reset();
}
reset() {
this.x = Math.random() * w + 200;
this.y = -50;
this.len = Math.random() * 120 + 80;
this.speed = Math.random() * 6 + 6;
this.angle = Math.PI / 4; // 45度倾斜划过
this.active = true;
}
update() {
this.x -= this.speed;
this.y += this.speed;
if (this.x < -this.len || this.y > h + this.len) {
this.active = false;
}
}
draw() {
if (!this.active) return;
const tailX = this.x + this.len * Math.cos(this.angle);
const tailY = this.y - this.len * Math.sin(this.angle);
const grad = ctx.createLinearGradient(this.x, this.y, tailX, tailY);
grad.addColorStop(0, 'rgba(255, 255, 255, 1)');
grad.addColorStop(0.3, 'rgba(160, 205, 255, 0.6)');
grad.addColorStop(1, 'rgba(160, 205, 255, 0)');
ctx.strokeStyle = grad;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(tailX, tailY);
ctx.stroke();
}
}
// 周期产生流星
setInterval(() => {
if (meteors.length < 5) {
meteors.push(new Meteor());
}
}, 1400);
function loop() {
ctx.fillStyle = '#05060d';
ctx.fillRect(0, 0, w, h);
// 绘制闪烁恒星
stars.forEach(s => {
s.alpha += s.speed;
const currentAlpha = (Math.sin(s.alpha) + 1) / 2 * 0.8 + 0.2;
ctx.fillStyle = `rgba(255, 255, 255, ${currentAlpha})`;
ctx.beginPath();
ctx.arc(s.x, s.y, s.radius, 0, Math.PI * 2);
ctx.fill();
});
// 绘制流星
for (let i = meteors.length - 1; i >= 0; i--) {
meteors[i].update();
meteors[i].draw();
if (!meteors[i].active) {
meteors.splice(i, 1);
}
}
requestAnimationFrame(loop);
}
loop();
</script>
</body>
</html>
1. 流星频率:修改 setInterval 的毫秒间隔(目前为 1400ms),调至 800ms 可以看到非常频繁的流星雨效果。
2. 划落角度:在 Meteor 类中,调整 this.angle 可改变流星下落的倾斜角。
3. 中心寄语:替换 <div class="star-message"> 内的标题与英文副标题即可完成文案定制。
特效四:浪漫樱花漫天飘落与相伴时光实时计时器
结合了微风摇曳的粉色樱花瓣物理运动与实时递增的时间计数器。计时器能将两人在一起的时间精确计算并换算为“XX 天 XX 小时 XX 分 XX 秒”。樱花花瓣通过 CSS 3D 转换进行带有景深的自旋与飘摆,极具视觉真实感。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>我们在一起的每一个瞬间</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: linear-gradient(135deg, #fdf6f0 0%, #fae8e0 100%);
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
min-height: 100vh;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
color: #4a3e3d;
}
.timer-card {
background: rgba(255, 255, 255, 0.85);
backdrop-filter: blur(8px);
padding: 40px 32px;
border-radius: 16px;
border: 1px solid rgba(255, 255, 255, 0.9);
box-shadow: 0 12px 32px rgba(220, 160, 150, 0.15);
text-align: center;
z-index: 10;
max-width: 520px;
width: 90%;
}
.couple-names {
font-size: 22px;
font-weight: bold;
color: #d15663;
margin-bottom: 12px;
}
.subtitle {
font-size: 14px;
color: #8c7370;
margin-bottom: 24px;
}
.counter-display {
display: flex;
justify-content: center;
gap: 12px;
margin: 20px 0;
}
.time-unit {
background: #ffffff;
padding: 12px 14px;
border-radius: 8px;
border: 1px solid #f2ded9;
min-width: 68px;
}
.time-val {
font-size: 24px;
font-weight: bold;
color: #d15663;
display: block;
}
.time-label {
font-size: 11px;
color: #a08b88;
}
.petal {
position: absolute;
background: radial-gradient(circle, #ffccd5 0%, #ffb3c1 100%);
border-radius: 15px 0px 15px 0px;
opacity: 0.85;
pointer-events: none;
}
</style>
</head>
<body>
<div class="timer-card">
<div class="couple-names">张同学 ❤️ 李同学</div>
<div class="subtitle">这是我们相识相恋的第:</div>
<div class="counter-display">
<div class="time-unit"><span class="time-val" id="days">00</span><span class="time-label">天</span></div>
<div class="time-unit"><span class="time-val" id="hours">00</span><span class="time-label">时</span></div>
<div class="time-unit"><span class="time-val" id="minutes">00</span><span class="time-label">分</span></div>
<div class="time-unit"><span class="time-val" id="seconds">00</span><span class="time-label">秒</span></div>
</div>
<p style="font-size: 13px; color: #8c7370; margin-top: 20px;">浮世三千,吾爱有三:日、月与卿。</p>
</div>
<script>
// ===== 自定义起始时间 =====
const START_DATE = new Date("2024-05-20T00:00:00"); // 替换为彼此相恋的日期时间
function updateTimer() {
const now = new Date();
const diff = now - START_DATE;
if (diff < 0) return;
const d = Math.floor(diff / (1000 * 60 * 60 * 24));
const h = Math.floor((diff / (1000 * 60 * 60)) % 24);
const m = Math.floor((diff / (1000 * 60)) % 60);
const s = Math.floor((diff / 1000) % 60);
document.getElementById('days').innerText = d;
document.getElementById('hours').innerText = h < 10 ? '0' + h : h;
document.getElementById('minutes').innerText = m < 10 ? '0' + m : m;
document.getElementById('seconds').innerText = s < 10 ? '0' + s : s;
}
setInterval(updateTimer, 1000);
updateTimer();
// 樱花飘落生成逻辑
function createPetal() {
const petal = document.createElement('div');
petal.className = 'petal';
const size = Math.random() * 10 + 12;
petal.style.width = size + 'px';
petal.style.height = (size * 1.3) + 'px';
petal.style.left = Math.random() * window.innerWidth + 'px';
petal.style.top = '-20px';
const duration = Math.random() * 5 + 4; // 下落耗时 4-9 秒
petal.style.transition = `transform ${duration}s linear, top ${duration}s linear`;
document.body.appendChild(petal);
setTimeout(() => {
petal.style.top = (window.innerHeight + 20) + 'px';
petal.style.transform = `rotate(${Math.random() * 720}deg) translateX(${(Math.random() - 0.5) * 150}px)`;
}, 50);
setTimeout(() => { petal.remove(); }, duration * 1000);
}
setInterval(createPetal, 260);
</script>
</body>
</html>
1. 起始日期配置:严格保持 new Date("YYYY-MM-DDTHH:mm:ss") 格式,替换为您真实的相恋日期。
2. 姓名修改:修改 <div class="couple-names"> 内的人名文本。
3. 花瓣密度控制:在代码末尾调整 setInterval(createPetal, 260),间隔时间越短花瓣越密集。
特效五:绚丽烟花粒子绽放与自定义名字光斑
烟花特效具备完备的物理重力加速度与空气摩擦阻力模拟。点击屏幕任何位置,都会立即从底部发射一枚升空引信,在点击坐标点爆炸成上百个向四周扩散的高速微粒;同时页面具备自动巡航发射机制,非常适合在节庆告白、跨年夜或特殊纪念日给对方带来惊喜。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>为你点亮盛夏烟火</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { background: #000000; overflow: hidden; height: 100vh; }
canvas { display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
.firework-title {
position: absolute;
top: 15%;
width: 100%;
text-align: center;
color: #ffffff;
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
font-size: 22px;
letter-spacing: 3px;
pointer-events: none;
text-shadow: 0 0 12px rgba(255, 200, 100, 0.8);
}
</style>
</head>
<body>
<div class="firework-title">✨ 点击屏幕 · 为你绽放专属烟花 ✨</div>
<canvas id="fireworkCanvas"></canvas>
<script>
const canvas = document.getElementById('fireworkCanvas');
const ctx = canvas.getContext('2d');
let width = canvas.width = window.innerWidth;
let height = canvas.height = window.innerHeight;
window.addEventListener('resize', () => {
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
});
const fireworks = [];
const particles = [];
const COLOR_PALETTE = ['#ff4d6d', '#ffd166', '#06d6a0', '#118ab2', '#ff9f1c', '#ffffff'];
class Firework {
constructor(targetX, targetY) {
this.x = targetX;
this.y = height;
this.targetY = targetY;
this.speed = Math.random() * 4 + 8;
this.color = COLOR_PALETTE[Math.floor(Math.random() * COLOR_PALETTE.length)];
this.exploded = false;
}
update() {
this.y -= this.speed;
if (this.y <= this.targetY) {
this.exploded = true;
this.createSparks();
}
}
createSparks() {
const count = 70;
for (let i = 0; i < count; i++) {
particles.push(new Spark(this.x, this.targetY, this.color));
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 3, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
class Spark {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
const angle = Math.random() * Math.PI * 2;
const velocity = Math.random() * 5 + 1;
this.vx = Math.cos(angle) * velocity;
this.vy = Math.sin(angle) * velocity;
this.alpha = 1;
this.friction = 0.95;
this.gravity = 0.12;
}
update() {
this.vx *= this.friction;
this.vy *= this.friction;
this.vy += this.gravity;
this.x += this.vx;
this.y += this.vy;
this.alpha -= 0.016; // 衰减消亡
}
draw() {
ctx.save();
ctx.globalAlpha = Math.max(this.alpha, 0);
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.shadowBlur = 6;
ctx.shadowColor = this.color;
ctx.fill();
ctx.restore();
}
}
// 交互触发
window.addEventListener('click', (e) => {
fireworks.push(new Firework(e.clientX, e.clientY));
});
// 自动随机发射
setInterval(() => {
fireworks.push(new Firework(Math.random() * width, Math.random() * (height * 0.5) + 50));
}, 1200);
function render() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(0, 0, width, height);
for (let i = fireworks.length - 1; i >= 0; i--) {
fireworks[i].update();
fireworks[i].draw();
if (fireworks[i].exploded) {
fireworks.splice(i, 1);
}
}
for (let i = particles.length - 1; i >= 0; i--) {
particles[i].update();
particles[i].draw();
if (particles[i].alpha <= 0) {
particles.splice(i, 1);
}
}
requestAnimationFrame(render);
}
render();
</script>
</body>
</html>
1. 发射密度:修改 setInterval 的时间间隔(目前为 1200ms),时间调得越短自动升空的烟花越密集。
2. 爆炸色彩:在 COLOR_PALETTE 数组中增删十六进制颜色值,例如仅保留 ['#ff4d6d', '#ffd166'] 可调出温馨暖金红的节日配色。
四、常见故障排查与上线避坑指南
当把制作好的页面发送给对方打开时,常常会遇到“在自己电脑上正常,对方手机打开却没有声音”、“画面边缘发虚模糊”或“页面可以左右晃动”等常见问题。以下决策树梳理了四大高频问题的核心成因与具体修复方案。
针对图 4 总结的关键问题,以下提供具体的修复代码与最佳实践:
1. 移动端 iOS 背景音乐无法自动播放的解决方案
苹果 iOS Safari 以及微信内置浏览器实行严格的媒体自动播放安全策略(Autoplay Policy),未经用户在当前页面发生触碰操作前,调用 audio.play() 会被直接拦截抛出异常。
标准解决方案:不要在 window.onload 中直接播放音频。而是在页面首屏添加一个半透明磨砂玻璃遮罩层(文案如“💌 点击开启为你准备的信件”),在用户的首个点击或触摸事件中触发播放并移除遮罩:
// 兼容 iOS 与微信的音频安全触发
const bgMusic = new Audio('music.mp3');
bgMusic.loop = true;
function unlockAudioAndStart() {
bgMusic.play().then(() => {
document.getElementById('maskOverlay').style.display = 'none';
}).catch(() => {
console.warn("音频播放受限,等待下一次点击");
});
}
// 针对微信端特有的 WeixinJSBridgeReady 监听
document.addEventListener("WeixinJSBridgeReady", function () {
bgMusic.play();
}, false);
2. Canvas 在高分辨率视网膜(Retina)屏幕下的高清校准
在 iPhone 等现代高分屏设备上,物理像素往往是 CSS 逻辑像素的 2 到 3 倍(即 window.devicePixelRatio >= 2)。如果仅仅将 Canvas 的 width 设置为 window.innerWidth,绘制出的粒子边缘会出现明显毛刺与模糊。
校准标准代码:
function setupHDCanvas(canvas, ctx) {
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
// 放大位图画布
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
// 保持 CSS 占位大小
canvas.style.width = rect.width + 'px';
canvas.style.height = rect.height + 'px';
// 坐标系缩放适配
ctx.scale(dpr, dpr);
}
3. 免费一键托管与二维码生成
修改完成后,若想将页面分享给他人,推荐使用 GitHub Pages 或 Vercel 进行免费部署:
- 将定制好的
index.html提交至 GitHub 仓库(命名为my-love-page)。 - 进入仓库的 Settings > Pages 选项卡,在 Build and deployment 中选择
Deploy from a branch,分支选择main并点击 Save。 - 约 1 分钟后,GitHub 会分配一个形如
https://username.github.io/my-love-page的专属外网链接。 - 将该网址复制到任意开源二维码生成工具(如各大浏览器自带的“为此页面创建二维码”功能),保存图片后即可直接通过微信发送给对方。
JavaScript退出浏览器全屏模式的方法
2026-11-17 13:01:27
不使用Canvas:怎么用DOM元素和CSS Grid实现JS俄罗斯方块
2026-11-17 09:46:24
邵山欢JS学习笔记:DOM操作与事件处理要点梳理
2026-11-17 08:37:17
浏览器JS脚本不生效怎么办?常见冲突与报错排查指南
2026-11-16 18:13:43
JS中DOMContentLoaded与window.onload的区别及适用场景
2026-11-16 15:05:11








