純JS代碼,快來下載吧!
Html部分:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>下雪</title>
<style>
body{
margin:0;
padding:0;
overflow:hidden;
}
</style>
</head>
<body>
<canvas id="Sonw" style=""></canvas>
<script type="text/javascript" src="Snow.js"></script>
</body>
</html>
Js部分:
window.onload = function () {
var Sonw = document.getElementById("Sonw");//獲取畫布對象
var SonwT = Sonw.getContext("2d");//獲取畫布的上下文
var w = window.innerWidth;//獲取瀏覽器屏幕的寬度
var h = window.innerHeight;//獲取瀏覽器屏幕的高度
Sonw.width = w;//設置canvas的寬度
Sonw.height = h;//設置canvas的高度
//如何產生雪花,一個圓 ,arc(x,y,r,start,end)
var num = 50;//初始化雪花數量
var snows = [];//雪花數組
for (var i = 0; i < num; i++) {
//x,y圓心掉的坐標位置,r代表圓的半徑,d每個圓的每個圓之間的間距,c代表的顏色
var r = randColor();
snows.push({
x: Math.random() * w,
y: Math.random() * h,
r: Math.random() * 3,
d: Math.random() * num
});
};
//繪畫的函數
function draw() {
SonwT.clearRect(0, 0, w, h);
SonwT.beginPath();
for (var i = 0; i < num; i++) {
var snow = snows[i];
//SonwT.fillStyle = randColor();
SonwT.fillStyle = "rgba(0,0,0,0.6)";
SonwT.moveTo(snow.x, snow.y);
SonwT.arc(snow.x, snow.y, snow.r, 0, Math.PI * 2);
}
SonwT.fill();
drop();//掉落
};
var angle = 0;
function drop() {
angle += 0.01;
for (var i = 0; i < num; i++) {
var p = snows[i];
//記住兩個公式:Math.sin(弧度)返回是一個0 1 -1 的數字
//math.cos(1 0 -1 ) 自由體,
p.y += Math.cos(angle + p.d) + 1 + p.r * 0.625;
p.x += Math.sin(angle) * 1;
//如果雪花到了邊界,進行邊界處理
if (p.x > w + 5 || p.x < -5 || p.y > h) {
if (i % 4 > 0) {
snows[i] = { x: Math.random() * w, y: -10, r: p.r, d: p.d };
} else {
//控制方向
if (Math.sin(angle) > 0) {
snows[i] = { x: -5, y: Math.random() * h, r: p.r, d: p.d };
} else {
snows[i] = { x: w + 5, y: Math.random() * h, r: p.r, d: p.d };
}
}
}
}
};
draw();//執行和調用函數
setInterval(draw, 10);
function randColor() {//隨機顏色
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + "," + g + "," + b + ")";
};
};
附件下載:Snowing.7z
版權屬於:zgcwkj
本文鏈接:https://www.zgcwkj.com/archives/9.html
轉載聲明:請注明本文章的標題及內容的出處和聲明,謝謝
感謝分享~