问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

炫彩爱心粒子动画的实现(HTML5 + Canvas)

创作时间:
作者:
@小白创作中心

炫彩爱心粒子动画的实现(HTML5 + Canvas)

引用
CSDN
1.
https://blog.csdn.net/qq_67010376/article/details/146202886

本文将分享一个使用HTML5 Canvas和JavaScript制作的炫彩爱心粒子特效。最终效果是一个不断闪烁、流动的五彩爱心,非常适合作为网页背景或情人节特效。

在这个项目中,我们将创建一个炫彩爱心粒子动画特效。这个特效使用HTML5 Canvas和JavaScript实现,效果是一个不断闪烁、流动的五彩爱心。以下是完整的代码实现:

<!DOCTYPE HTML>
<HTML>
<HEAD>
  <TITLE>Hacker6 </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: #000;
    }
    #canvasWrapper {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
    }
    canvas {
      width: 80%; /* Set canvas width to 80% of the original size */
      height: 80%; /* Set canvas height to 80% of the original size */
    }
  </style>
</HEAD>
<BODY>
  <div id="canvasWrapper">
    <canvas id="pinkboard"></canvas>
  </div>
<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
      },
    };
/*
* 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;
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, // 生成粒子速率
        time;
    function pointOnHeart(t) {
        return new Point(
            96 * Math.pow(Math.sin(t), 3),
            78 * Math.cos(t) - 30 * Math.cos(2 * t) - 12 * Math.cos(3 * t) - 6 * Math.cos(4 * t) + 15
        );
    }
    // 修改 Particle 类,添加随机颜色
    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;
        this.age = 0;
        // 生成一个随机颜色(HSL 颜色模式)
        this.color = `hsl(${Math.random() * 360}, 100%, 60%)`;
    };
    // 修改 draw 方法,使用粒子的随机颜色
    Particle.prototype.draw = function(context) {
        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 = this.color; // 使用粒子的随机颜色
        context.fill();
    };
    function render() {
        requestAnimationFrame(render);
        var newTime = new Date().getTime() / 1000,
            deltaTime = newTime - (time || newTime);
        time = newTime;
        context.clearRect(0, 0, canvas.width, canvas.height);
        var amount = particleRate * deltaTime;
        for (var i = 0; i < amount; i++) {
            var pos = pointOnHeart(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);
        }
        particles.update(deltaTime);
        particles.draw(context);
    }
    function onResize() {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
    }
    window.addEventListener('resize', onResize);
    onResize();
    render();
})(document.getElementById('pinkboard'));
</script>
</BODY>
</HTML>  

运行效果如下:

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号