本文将介绍如何使用 HTML、CSS 和 JavaScript 实现一个渐变蝴蝶效果。该效果包括以下核心功能:
1. 蝴蝶形状的粒子效果:通过极坐标方程生成蝴蝶形状的粒子。
2. 渐变色:中心区域和粒子使用相同的渐变色,颜色动态变化。
3. 重力效果:粒子在扩散的同时受到重力影响,产生下坠效果。
4. 中心填充:中心区域填充为渐变色,与粒子颜色一样。
1. HTML 结构
HTML 部分非常简单,只需要一个 `<canvas>` 元素用于绘制动画。
<!DOCTYPE HTML>
<HTML>
<HEAD>
<meta charset="utf-8">
<TITLE>Butterfly Particles</TITLE>
<style>
html, body {
height: 100%;
padding: 0;
margin: 0;
background:#000000;
}
canvas {
position: absolute;
width: 100%;
height: 100%;
}
</style>
</HEAD>
<BODY>
<canvas id="pinkboard"></canvas>
</BODY>
</HTML>
2. JavaScript 实现
2.1 设置参数
定义粒子和动画的参数,包括粒子数量、速度、大小、重力加速度等。
var settings = {
particles: {
length: 500, // 粒子数量
duration: 2, // 粒子生命周期
velocity: 100, // 粒子速度
effect: -0.75, // 粒子效果
size: 30, // 粒子大小
},
gravity: 50, // 重力加速度
centerRadius: 50 // 中心圆半径
};
2.2 颜色渐变设置
定义渐变色参数,包括渐变时间和颜色变化范围。
var gradientDuration = 5; // 渐变时间
var startHue = Math.random() * 360; // 初始色相
var targetHue = Math.random() * 360; // 目标色相
var gradientStartTime = 0; // 渐变开始时间
2.3 蝴蝶形状的极坐标方程
使用极坐标方程 生成蝴蝶形状的坐标。
function pointOnButterfly(t) {
var r = Math.exp(Math.cos(9 * t)) - 2 * Math.cos(4 * t);
return new Point(
r * Math.cos(t) * 50, // 放大倍数
r * Math.sin(t) * 50 // 放大倍数
);
}
2.4 粒子类
定义粒子类,包括粒子的位置、速度、加速度和生命周期。
var Particle = (function() {
function Particle() {
this.position = new Point();
this.velocity = new Point();
this.acceleration = new Point();
this.age = 0;
}
Particle.prototype.initialize = function(x, y, dx, dy) {
this.position.x = x;
this.position.y = y;
this.velocity.x = dx;
this.velocity.y = dy;
this.acceleration.x = dx * settings.particles.effect;
this.acceleration.y = dy * settings.particles.effect + settings.gravity; // 添加重力效果
this.age = 0;
};
Particle.prototype.update = function(deltaTime) {
this.position.x += this.velocity.x * deltaTime;
this.position.y += this.velocity.y * deltaTime;
this.velocity.x += this.acceleration.x * deltaTime;
this.velocity.y += this.acceleration.y * deltaTime;
this.age += deltaTime;
};
Particle.prototype.draw = function(context, gradient) {
function ease(t) {
return (--t) * t * t + 1;
}
var size = settings.particles.size * ease(this.age / settings.particles.duration);
context.globalAlpha = 1 - this.age / settings.particles.duration;
context.beginPath();
context.arc(this.position.x, this.position.y, size / 2, 0, Math.PI * 2);
context.fillStyle = gradient;
context.fill();
};
return Particle;
})();
2.5主动画逻辑
初始化画布,生成粒子并渲染动画。
(function(canvas) {
var context = canvas.getContext('2d'),
particles = new ParticlePool(settings.particles.length),
particleRate = settings.particles.length / settings.particles.duration, // particles/sec
time,
hue = 0; // 颜色变化控制
// 创建渐变色
function createGradient(x, y, size) {
var gradient = context.createRadialGradient(x, y, 0, x, y, size);
gradient.addColorStop(0, `hsl(${hue}, 100%, 70%)`);
gradient.addColorStop(0.5, `hsl(${(hue + 60) % 360}, 100%, 60%)`);
gradient.addColorStop(1, `hsl(${(hue + 120) % 360}, 100%, 50%)`);
return gradient;
}
// render that thing!
function render() {
// next animation frame
requestAnimationFrame(render);
// update time
var newTime = new Date().getTime() / 1000,
deltaTime = newTime - (time || newTime);
time = newTime;
hue = (hue + 1) % 360; // 让颜色不断变化
// clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// 创建渐变色
var gradient = createGradient(canvas.width / 2, canvas.height / 2, 100);
// 绘制中心圆
context.beginPath();
context.arc(canvas.width / 2, canvas.height / 2, settings.centerRadius, 0, Math.PI * 2);
context.fillStyle = gradient;
context.fill();
// create new particles
var amount = particleRate * deltaTime;
for (var i = 0; i < amount; i++) {
var pos = pointOnButterfly(Math.PI - 2 * Math.PI * Math.random());
var dir = pos.clone().length(settings.particles.velocity);
particles.add(canvas.width / 2 + pos.x, canvas.height / 2 - pos.y, dir.x, -dir.y);
}
// update and draw particles
particles.update(deltaTime);
particles.draw(context, gradient);
}
// handle (re-)sizing of the canvas
function onResize() {
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
}
window.onresize = onResize;
// delay rendering bootstrap
setTimeout(function() {
onResize();
render();
}, 10);
})(document.getElementById('pinkboard'));
完整代码
<!DOCTYPE HTML>
<HTML>
<HEAD>
<meta charset="utf-8">
<TITLE>Butterfly Particles</TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<style>
html, body {
height: 100%;
padding: 0;
margin: 0;
background:#000000;
}
canvas {
position: absolute;
width: 100%;
height: 100%;
}
</style>
</HEAD>
<BODY>
<canvas id="pinkboard"></canvas>
<script>
/*
* Settings
*/
var settings = {
particles: {
length: 500, // maximum amount of particles
duration: 2, // particle duration in sec
velocity: 100, // particle velocity in pixels/sec
effect: -0.75, // play with this for a nice effect
size: 30, // particle size in pixels
},
gravity: 50, // 重力加速度,单位为像素/秒²
centerRadius: 50 // 中心圆半径
};
/*
* Gradient settings
*/
var gradientDuration = 5; // 渐变时间,单位为秒
var startHue = Math.random() * 360; // 初始随机基色
var targetHue = Math.random() * 360; // 目标随机基色
var gradientStartTime = 0; // 渐变开始时间
/*
* RequestAnimationFrame polyfill by Erik Möller
*/
(function(){var b=0;var c=["ms","moz","webkit","o"];for(var a=0;a<c.length&&!window.requestAnimationFrame;++a){window.requestAnimationFrame=window[c[a]+"RequestAnimationFrame"];window.cancelAnimationFrame=window[c[a]+"CancelAnimationFrame"]||window[c[a]+"CancelRequestAnimationFrame"]}if(!window.requestAnimationFrame){window.requestAnimationFrame=function(h,e){var d=new Date().getTime();var f=Math.max(0,16-(d-b));var g=window.setTimeout(function(){h(d+f)},f);b=d+f;return g}}if(!window.cancelAnimationFrame){window.cancelAnimationFrame=function(d){clearTimeout(d)}}}());
/*
* Point class
*/
var Point = (function() {
function Point(x, y) {
this.x = (typeof x !== 'undefined') ? x : 0;
this.y = (typeof y !== 'undefined') ? y : 0;
}
Point.prototype.clone = function() {
return new Point(this.x, this.y);
};
Point.prototype.length = function(length) {
if (typeof length == 'undefined')
return Math.sqrt(this.x * this.x + this.y * this.y);
this.normalize();
this.x *= length;
this.y *= length;
return this;
};
Point.prototype.normalize = function() {
var length = this.length();
this.x /= length;
this.y /= length;
return this;
};
return Point;
})();
/*
* Particle class
*/
var Particle = (function() {
function Particle() {
this.position = new Point();
this.velocity = new Point();
this.acceleration = new Point();
this.age = 0;
}
Particle.prototype.initialize = function(x, y, dx, dy) {
this.position.x = x;
this.position.y = y;
this.velocity.x = dx;
this.velocity.y = dy;
this.acceleration.x = dx * settings.particles.effect;
this.acceleration.y = dy * settings.particles.effect + settings.gravity; // 添加重力效果
this.age = 0;
};
Particle.prototype.update = function(deltaTime) {
this.position.x += this.velocity.x * deltaTime;
this.position.y += this.velocity.y * deltaTime;
this.velocity.x += this.acceleration.x * deltaTime;
this.velocity.y += this.acceleration.y * deltaTime;
this.age += deltaTime;
};
Particle.prototype.draw = function(context, gradient) {
function ease(t) {
return (--t) * t * t + 1;
}
var size = settings.particles.size * ease(this.age / settings.particles.duration);
context.globalAlpha = 1 - this.age / settings.particles.duration;
context.beginPath();
context.arc(this.position.x, this.position.y, size / 2, 0, Math.PI * 2);
context.fillStyle = gradient;
context.fill();
};
return Particle;
})();
/*
* ParticlePool class
*/
var ParticlePool = (function() {
var particles,
firstActive = 0,
firstFree = 0,
duration = settings.particles.duration;
function ParticlePool(length) {
// create and populate particle pool
particles = new Array(length);
for (var i = 0; i < particles.length; i++)
particles[i] = new Particle();
}
ParticlePool.prototype.add = function(x, y, dx, dy) {
particles[firstFree].initialize(x, y, dx, dy);
// handle circular queue
firstFree++;
if (firstFree == particles.length) firstFree = 0;
if (firstActive == firstFree ) firstActive++;
if (firstActive == particles.length) firstActive = 0;
};
ParticlePool.prototype.update = function(deltaTime) {
var i;
// update active particles
if (firstActive < firstFree) {
for (i = firstActive; i < firstFree; i++)
particles[i].update(deltaTime);
}
if (firstFree < firstActive) {
for (i = firstActive; i < particles.length; i++)
particles[i].update(deltaTime);
for (i = 0; i < firstFree; i++)
particles[i].update(deltaTime);
}
// remove inactive particles
while (particles[firstActive].age >= duration && firstActive != firstFree) {
firstActive++;
if (firstActive == particles.length) firstActive = 0;
}
};
ParticlePool.prototype.draw = function(context, gradient) {
// draw active particles
if (firstActive < firstFree) {
for (i = firstActive; i < firstFree; i++)
particles[i].draw(context, gradient);
}
if (firstFree < firstActive) {
for (i = firstActive; i < particles.length; i++)
particles[i].draw(context, gradient);
for (i = 0; i < firstFree; i++)
particles[i].draw(context, gradient);
}
};
return ParticlePool;
})();
/*
* Putting it all together
*/
(function(canvas) {
var context = canvas.getContext('2d'),
particles = new ParticlePool(settings.particles.length),
particleRate = settings.particles.length / settings.particles.duration, // particles/sec
time,
hue = 0; // 颜色变化控制
// 蝴蝶形状的极坐标方程
function pointOnButterfly(t) {
var r = Math.exp(Math.cos(9 * t)) - 2 * Math.cos(4 * t);
return new Point(
r * Math.cos(t) * 50, // 放大倍数
r * Math.sin(t) * 50 // 放大倍数
);
}
// 创建渐变色
function createGradient(x, y, size) {
var gradient = context.createRadialGradient(x, y, 0, x, y, size);
gradient.addColorStop(0, `hsl(${hue}, 100%, 70%)`);
gradient.addColorStop(0.5, `hsl(${(hue + 60) % 360}, 100%, 60%)`);
gradient.addColorStop(1, `hsl(${(hue + 120) % 360}, 100%, 50%)`);
return gradient;
}
// render that thing!
function render() {
// next animation frame
requestAnimationFrame(render);
// update time
var newTime = new Date().getTime() / 1000,
deltaTime = newTime - (time || newTime);
time = newTime;
hue = (hue + 1) % 360; // 让颜色不断变化
// clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// 创建渐变色
var gradient = createGradient(canvas.width / 2, canvas.height / 2, 100);
// 绘制中心圆
context.beginPath();
context.arc(canvas.width / 2, canvas.height / 2, settings.centerRadius, 0, Math.PI * 2);
context.fillStyle = gradient;
context.fill();
// create new particles
var amount = particleRate * deltaTime;
for (var i = 0; i < amount; i++) {
var pos = pointOnButterfly(Math.PI - 2 * Math.PI * Math.random());
var dir = pos.clone().length(settings.particles.velocity);
particles.add(canvas.width / 2 + pos.x, canvas.height / 2 - pos.y, dir.x, -dir.y);
}
// update and draw particles
particles.update(deltaTime);
particles.draw(context, gradient);
}
// handle (re-)sizing of the canvas
function onResize() {
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
}
window.onresize = onResize;
// delay rendering bootstrap
setTimeout(function() {
onResize();
render();
}, 10);
})(document.getElementById('pinkboard'));
</script>
</BODY>
</HTML>
运行效果
点击查看效果
总结
通过极坐标方程生成蝴蝶形状,结合渐变色和重力效果,实现了动态的渐变蝴蝶动画。数学知识(如极坐标方程、向量运算、运动学公式)是代码的核心,展现了数学在编程和设计中的重要性。