jscanvas实现随机粒⼦特效本⽂实例为⼤家分享了js canvas随机粒⼦特效的具体代码,供⼤家参考,具体内容如下
前⾔
canvas实现前端的特效美术
结果展⽰
代码
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./main.js"></script>
</body>
</html>
main.js
/*
*粒⼦化类构造
*类功能:
*1.初始化。创建画布,规定粒⼦属性等;
*2.创建图像并且进⾏绘制
*3.区域颜⾊定义
*4.粒⼦移动和偏射⾓度
*/
// ⽣成粒⼦
let Particle = function(context, options){
let random = Math.random();
// 在画布⾥的x坐标
this.x = options.x;
// 在画布⾥的y坐标
this.y = options.y;
// 取随机数的1/2,对⾓度进⾏随机放⼤
this.s = 0.5 + Math.random();
/
/ this.s = 1 + Math.random();
// 粒⼦运动的变化⾓度
this.a = 0;
// 宽度
this.w = window.innerWidth;
// ⾼度
this.h = window.innerHeight;
this.radius = options.radius || 0.5 + Math.random() * 10;
// 颜⾊
// console.lor);
/
/ 指定3秒后调⽤;
// 如果粒⼦的半径⼤于0.5,加⼊新的粒⼦。
setTimeout(function(){
if(this.radius > 0.5){
particles.push(
new Particle(context, {
x: this.x,
y: this.y,
color: this.radius / 2 > 1 ? "#d6433b" : "#FFFFFF",                  radius: this.radius / 2.2 })
);
}
}.call(Particle), 3000);
};
// 渲染图像
der = function() {
//从(0,0)开始新的路径;
// 创建曲线弧
//颜⾊填充
/
/ 填充当前图像的路径
// 返回初始点,并且绘制线条到初始位置
};
Particle.prototype.swapColor = function() {
// 排除⽩⾊
if (lor != "#FFFFFF") {
// 判断左右界⾯,并且赋颜⾊的值
if (this.x < this.w / 2) {
// 左半边
} else {
// 右半边
}
}
};
ve = function() {
// 颜⾊定义
this.swapColor();
// 横坐标按照cos⾓度进⾏变换,并且对其进⾏随机数放⼤;    // 偏射⾓度以便两个半界分开
this.x += s(this.a) * this.s;
this.y += Math.sin(this.a) * this.s;
// this.y += s(this.a) * this.s;
// this.x += Math.sin(this.a) * this.s;
// 在变化后,对随机⾓度进⾏再重取;
this.a += Math.random() * 0.8 - 0.4;
// 判断全为0,粒⼦横坐标⽆移动;
if (this.x < 0 || this.x > this.w - this.radius) {
return false;
}
// 粒⼦纵坐标⽆移动;
if (this.y < 0 || this.y > this.h - this.radius) {
return false;
}
// 重新绘制图像
return true;
};
let canvas = ateElement('canvas');
canvas.width = window.innerWidth - 20;
canvas.height = window.innerHeight - 30;
document.body.insertBefore(canvas, null);实现特效的代码js
let context = Context('2d');
frequency: 50,
x: canvas.width,
y: canvas.height
};
let particles = [],
frequency = conf.frequency;
setInterval(function(){
popolate();
}.bind(null), frequency);
function popolate(){
particles.push(
new Particle(context, {
x: conf.x / 2,
y: conf.y / 2
})
);
return particles.length;
}
function clear() {
context.globalAlpha = 0.04;
context.fillStyle = '#000042';
context.fillRect(0,0,canvas.width, canvas.height);
context.globalAlpha = 1;
}
function update(){
particles = particles.filter(p => p.move());
clear();
requestAnimationFrame(arguments.callee);
}
update();
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。