文章详情
canvas基础—简单粒子动画(下)
标签:
  • canvas
  • javascript
日期:2020-6-30 11:44
摘要:canvas是h5新增的组件,它就像一块幕布,可以用javascript在上面绘制各种图表、动画等...

效果:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>原谅绿粒子</title>
</head>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#canvas {
background: #000;
display: block;
}
</style>
<body>
<canvas id="canvas"></canvas>
</body>
<script type="text/javascript">
// 获取画布节点
var myCanvas = document.getElementById('canvas');
// 设置画布的宽高等于浏览器可视区域
myCanvas.width = document.documentElement.clientWidth;
myCanvas.height = document.documentElement.clientHeight;
// 初始化canvas
var ctx = myCanvas.getContext('2d');
// 建立所有小球的数组
var ballArr = [];
// Ball类,传坐标和速度
function Ball(x, y, speed) {
this.x = x;
this.y = y;
// 小球的半径
this.r = 2;
// 小球的透明度 opacity 0-1之间随机
this.o = Math.random();
// 速度随机处理,让每个小球的速度有波动
this.speed = Math.random() * speed;
// 随机x和y的增量,可以让小球往任意方向运动(直角坐标系象限分布的原理)
this.diffX = (Math.random() * 4 - 2) * this.speed; // 每次渲染x的增量在-2到+2之间再乘以speed系数
this.diffY = (Math.random() * 4 - 2) * this.speed; // 每次渲染y的增量在-2到+2之间再乘以speed系数
// 设置颜色和透明度
this.fillStyle = 'rgba(171,229,115,' + this.o + ')';
// 小球初始化创建好后 置入数组
ballArr.push(this);
}
// 渲染每一帧的方法
Ball.prototype.render = function() {
// 开始路径
ctx.beginPath();
// 设置颜色
ctx.fillStyle = this.fillStyle;
// 加上投影
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = 12;
ctx.shadowColor = 'rgba(171,229,115,1)';
// 绘制小球
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
ctx.fill();
}
// 改变每一帧的方法
Ball.prototype.change = function() {
this.x += this.diffX;
this.y += this.diffY;
this.r += 0.2;
this.o -= 0.008;
this.fillStyle = 'rgba(171,229,115,' + this.o + ')';
// 当小球达到一定大小 在数组里删除掉这个小球
if (this.r >= 30) {
for (var i = 0; i < ballArr.length; i++) {
if (ballArr[i] == this) {
ballArr.splice(i, 1);
// 已经删掉了 直接跳出循环
break;
}
}
}
}
var x = document.body.clientWidth / 2;
var y = document.body.clientHeight / 2;
// 定时器 每秒50帧
setInterval(function() {
// 每次渲染之前都需要清屏
ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
for (var i = 0; i < ballArr.length; i++) {
ballArr[i].render();
ballArr[i].change();
}
new Ball(x, y, 1)
new Ball(x, y, 2)
}, 20);
</script>
</html>

发送
评论(0)