<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="js/test.js"></script>
<title>粒子发生器</title>
</head>
<style>
#canvas1 {
width: 400px;
height:400px;
border: 1px solid red;
background-color: bisque;
}
</style>
<body>
<canvas id = 'canvas1' width="400" height="400"></canvas>
<script>
var Game = new Particle(document.querySelector('#canvas1'));
</script>
</body>
</html>
(function (){
var Model = function (canvas){
var me = this;
me.canvas = canvas;
me.ctx = canvas.getContext('2d');
me.number = 100;
me.particles = [];
me.genParticle();
var x= me.init()
const {particles} = me;
setInterval(function(){me.draw(particles)},120);
}
window.Particle = Model;
//定义一个成员函数,生成粒子
Model.prototype.genParticle = function (){
var me = this;
return {
x:me.canvas.width/2,
y:me.canvas.height/2,
vector:{x:0,y:0},
//粒子速度和方向
direction :2 * Math.PI * Math.random(),
speed : Math.random() * 10,
//大小,颜色
radius : Math.round(Math.random()*10),
r:Math.floor(Math.random()*255),
g:Math.floor(Math.random()*255),
b:Math.floor(Math.random()*255),
a:(Math.random()),
}
}
//在canvas上绘制粒子
Model.prototype.draw = function (particle){
var me = this;
const {ctx} = me;
ctx.clearRect(0,0,me.canvas.width,me.canvas.height)
for(item of me.particles)
{
const {x, y, speed, direction, radius,r,g,b,a,particles} = item;
ctx.beginPath();
ctx.fillStyle = 'rgba('+[r,g,b,a]+')'
ctx.arc(x,y,radius,0,2*Math.PI);
ctx.strokeStyle = 'bisque'
ctx.stroke();
ctx.fill();
ctx.closePath();
item.vector = {
x:speed * Math.cos(direction), //粒子在x轴的速度
y:speed * Math.sin(direction) //粒子在y轴的速度
};
}
me.run();
}
//初始化100个粒子
Model.prototype.init = function (){
var me = this;
const {number,particles,genParticle} = me;
if(particles.length === 0)
{
for (var i=0; i<number; i++)
{
particles[i] = me.genParticle();
}
}
else{
particles.push(me.genParticle())
}
}
Model.prototype.run = function() {
var me = this;
const {number,particles,genParticle,ctx} = me;
for(var i = 0;i <number; i++)
{
const {r,g,b} = me.particles[i];
me.particles[i].x += particles[i].vector.x;
me.particles[i].y += particles[i].vector.y;
me.particles[i].a=me.particles[i].a-0.01;
ctx.fillStyle = 'rgba('+[r,g,b,me.particles[i].a]+')'
console.log(particles[i].a);
if(particles[i].a <= 0)
{
me.particles.splice(i, 1);
me.init();
}
// if(me.particles[i].x > me.canvas.width || me.particles[i].y > me.canvas.height||me.particles[i].x < 0 || me.particles[i].y < 0)
// {
// me.particles.splice(i, 1);
// me.init();
// }
}
}
}
())