<!doctype html><!--聲明文檔類型:html-->
<html lang="en">
<head><!--頭部-->
<meta charset="UTF-8"><!--字符編碼:utf-8國際編碼-->
<meta name="Keywords"content="關鍵詞1,關鍵詞2"><!--關鍵詞-->
<meta name="Description"content="描述"><!--描述-->
<title>流星雨</title><!--網頁標題-->
<style>
*{
margin:0;
padding:0;
}
#canvas{
background:#000;
display:block;
}
</style>
</head>
<body><!--身體-->
<canvas id="canvas">您的瀏覽器不支持cnavas繪圖,請您更換瀏覽器!!</canvas>
<script>
var can = document.getElementById("canvas");
var ctx = can.getContext("2d");//設置繪圖環境
var w = can.width =window.innerWidth;//把窗口的寬度賦值給畫布
var h = can.height =window.innerHeight;//把窗口的高度賦值給畫布
var count = 30;//雨滴的個數
var drops = [];//定義一個空數組來保存雨滴個數
//瀏覽器窗口改變的時候重新獲取寬度
window.onresize =function(){
w = can.width = window.innerWidth;
h = can.height = window.innerHeight;
}
function Drop(){}//定義雨滴對象
//添加原型對象方法
Drop.prototype = {
init : function(){//初始化
this.x =random(0,w);
this.y =0;
this.r =1;//初始半徑
this.vy =random(4,5);//豎直方向的加速度 //從4~5之間的隨機數
this.vr =1;//半徑的加速度
this.a =1;//初始透明度
this.va =0.96;//透明度的變化係數
this.l =random(h*0.8,h*0.9);//雨滴下落的高度
},
draw : function(){//繪製
if (this.y >this.l)
{
ctx.beginPath();//一個畫布中開始子路徑的一個新的集合。丟棄任何當前定義的路徑並且開始一條新的路徑。它把當前的點設置爲 (0,0)。
ctx.arc(this.x,this.y,this.r,0,2*Math.PI,false);//創建一個圓形 this.x圓的中心的 x 座標。 this.y圓的中心的 y 座標。 this.r圓的半徑。 0 起始角,以弧度計。(弧的圓形的三點鐘位置是 0 度)。 2*Math.PI結束角,以弧度計。 false可選。規定應該逆時針還是順時針繪圖。False = 順時針,true = 逆時針。
ctx.strokeStyle ="rgba(0,255,255,"+this.a+")";//strokeStyle 屬性設置或返回用於筆觸的顏色、漸變或模式。
ctx.stroke();//繪製出來路徑
}else{
console.log(this.a)
ctx.fillStyle =color(this.a);//透明度
// console.log(ctx.fillStyle);
ctx.fillRect(this.x,this.y,2,10);//繪製"已填充"的矩形。默認的填充顏色是黑色。
}
this.update();
},
//更新座標
update : function(){
if (this.y <this.l)
{
this.y +=this.vy;
}else{
if (this.a >0.03)
{
this.r +=this.vr;
if (this.r >50)
{
this.a *=this.va;
}
}else{
this.init();
}
}
}
}
//不斷的更新雨滴位置
function move(){
ctx.fillStyle ="rgba(0,0,0,.1)";
ctx.fillRect(0,0,w,h);//這個在先繪製
for (var i=0;i<drops.length;i++ )
{
drops[i].draw();
}
//調用經動畫
requestAnimationFrame(move);
}
//創建一個雨滴實例對象
//var drop = new Drop();
//drop.init();
//drop.draw();
//延遲產生每個雨滴
function setup(){
for (var i=0;i <count ;i++ )
{
(function(j){
setTimeout(function(){
var drop = new Drop();
drop.init();
drops.push(drop);
},j*200);
}(i))
}
}
setup();
move();
//封裝一個產生隨機數的方法
function random(min,max){
return Math.random()*(max-min) +min;
}
//封裝一個隨機顏色
function color(a){
//rgba
var r = Math.floor(Math.random()*255);
var g = Math.floor(Math.random()*255);
var b = Math.floor(Math.random()*255);
return "rgba("+r+","+g+","+b+","+a+")"
}
</script>
</body>
<html>
canvas實現雨滴動畫
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.