1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<meta name="keywords" content=""/>
<meta name="description" content=""/>
<style type="text/css">
* {
margin: 0;padding: 0;
}
html,body {
width: 100%;
height: 100%;
overflow: hidden;
}
canvas {
background: #000;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas'),
c = canvas.getContext('2d'),
oW,
oH,
// 粒子的个数
count,
// 速度
speed = 5,
// 装粒子的数组
dotteds = [];
// 获取与设置宽高
function getAndSet(){
// 获取
oW = window.innerWidth || document.body.clientWidth;
oH = window.innerHeight || document.body.clientHeight;
// 设置
canvas.width = oW;
canvas.height = oH;
// 粒子的个数
count = Math.floor(oW * oH / 3000);
console.log(count);
}
getAndSet();
// 窗口大小改变
window.onresize = function(){
getAndSet();
}
// 生成粒子
for (var i = 0; i < count; i++) {
dotteds.push(new Dotted(i * Math.floor(Math.random() * 361)))
}
// 创建单个例子对象
function Dotted(hue){
// 单个例子的起始坐标
this.x = Math.random() * oW;
this.y = Math.random() * oH;
this.r = Math.random() * 3 + 1;
// 单个粒子的速度
this.vx = (Math.random()-0.5) * speed || 1;
this.vy = (Math.random()-0.5) * speed || 1;
// 颜色值
this.hue = hue;
}
// 粒子速度更新
Dotted.prototype.update = function(){
this.x += this.vx;
this.y += this.vy;
if (this.x < 0 || this.x > oW) {
this.vx *= -1;
this.r = Math.random() * 3 + 1;
this.hue = Math.floor(Math.random() * 361);
}
if (this.y < 0 || this.y > oH) {
this.vy *= -1;
this.r = Math.random() * 3 + 1;
this.hue = Math.floor(Math.random() * 361);
}
}
function move(){
window.requestAnimationFrame(move);
c.clearRect(0,0,oW,oH);
// c.fillStyle = 'rgba(0,0,0,.2)';
// c.fillRect(0,0,oW,oH);
for (var i = 0; i < dotteds.length; i++) {
var d = dotteds[i];
d.update();
c.beginPath();
c.arc(d.x,d.y,d.r,0,Math.PI*2,true);
c.fillStyle = 'hsl('+ d.hue +',50% , 50%)';
c.fill();
}
}
move();
</script>
</body>
</html> |
共 0 条评论关于"Canvas制作的粒子效果"
最新评论