JS+Canvas 實現(xiàn)下雨下雪效果
最近做了一個項目,其中有需求要實現(xiàn)下雨小雪的動畫特效,所以在此做了個drop組件,來展現(xiàn)這種canvas常見的下落物體效果。在沒給大家介紹正文之前,先給大家展示下效果圖:
展示效果圖:
下雨 下雪

看起來效果還是不錯的,相對于使用創(chuàng)建dom元素來制作多物體位移動畫, 使用canvas會更加容易快捷,以及性能會更好
調(diào)用代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#canvas{
width:100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="canvasDrop.js"></script>
<script>
canvasDrop.init({
type: "rain", // drop類型,有rain or snow
speed : [0.4,2.5], //速度范圍
size_range: [0.5,1.5],//大小半徑范圍
hasBounce: true, //是否有反彈效果or false,
wind_direction: -105 //角度
hasGravity: true //是否有重力考慮
});
</script>
</body>
</html>
好了,接下來講解一下簡單的實現(xiàn)原理 首先,先定義一些我們會用到的全局變量,如風向角度,幾率,對象數(shù)據(jù)等
定義全局變量
//定義兩個對象數(shù)據(jù)
//分別是drops下落物體對象
//和反彈物體bounces對象
var drops = [], bounces = [];
//這里設(shè)定重力加速度為0.2/一幀
var gravity = 0.2;
var speed_x_x, //橫向加速度
speed_x_y, //縱向加速度
wind_anger; //風向
//畫布的像素寬高
var canvasWidth,
canvasHeight;
//創(chuàng)建drop的幾率
var drop_chance;
//配置對象
var OPTS;
//判斷是否有requestAnimationFrame方法,如果有則使用,沒有則大約一秒30幀
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 30);
};
定義核心對象
接下來我們需要定義幾個重要的對象 該組織所需定義的對象也比較少,總共才三個 在整個drop組件中共定義了`三個核心對象,分別是如下:
Vector 速度對象,帶有橫向x,和縱向y的速度大小 單位為:V = 位移像素/幀
對于Vector對象的理解也十分簡單粗暴,就是記錄下落對象drop的速度/V
var Vector = function(x, y) {
//私有屬性 橫向速度x ,縱向速度y
this.x = x || 0;
this.y = y || 0;
};
//公有方法- add : 速度改變函數(shù),根據(jù)參數(shù)對速度進行增加
//由于業(yè)務(wù)需求,考慮的都是下落加速的情況,故沒有減速的,后期可拓展
/*
* @param v object || string
*/
Vector.prototype.add = function(v) {
if (v.x != null && v.y != null) {
this.x += v.x;
this.y += v.y;
} else {
this.x += v;
this.y += v;
}
return this;
};
//公有方法- copy : 復(fù)制一個vector,來用作保存之前速度節(jié)點的記錄
Vector.prototype.copy = function() {
//返回一個同等速度屬性的Vector實例
return new Vector(this.x, this.y);
};
Drop 下落物體對象, 即上面效果中的雨滴和雪, 在后面你也可自己拓展為隕石或者炮彈
對于Drop對象其基本定義如下
//構(gòu)造函數(shù)
var Drop = function() {
/* .... */
};
//公有方法-update
Drop.prototype.update = function() {
/* .... */
};
//公有方法-draw
Drop.prototype.draw = function() {
/* .... */
};
看了上面的三個方法,是否都猜到他們的作用呢,接下來讓我們了解這三個方法做了些什么
構(gòu)造函數(shù)
構(gòu)造函數(shù)主要負責定義drop對象的初始信息,如速度,初始坐標,大小,加速度等
//構(gòu)造函數(shù) Drop
var Drop = function() {
//隨機設(shè)置drop的初始坐標
//首先隨機選擇下落對象是從從哪一邊
var randomEdge = Math.random()*2;
if(randomEdge > 1){
this.pos = new Vector(50 + Math.random() * canvas.width, -80);
}else{
this.pos = new Vector(canvas.width, Math.random() * canvas.height);
}
//設(shè)置下落元素的大小
//通過調(diào)用的OPTS函數(shù)的半徑范圍進行隨機取值
this.radius = (OPTS.size_range[0] + Math.random() * OPTS.size_range[1]) *DPR;
//獲得drop初始速度
//通過調(diào)用的OPTS函數(shù)的速度范圍進行隨機取值
this.speed = (OPTS.speed[0] + Math.random() * OPTS.speed[1]) *DPR;
this.prev = this.pos;
//將角度乘以 0.017453293 (2PI/360)即可轉(zhuǎn)換為弧度。
var eachAnger = 0.017453293;
//獲得風向的角度
wind_anger = OPTS.wind_direction * eachAnger;
//獲得橫向加速度
speed_x = this.speed * Math.cos(wind_anger);
//獲得縱向加速度
speed_y = - this.speed * Math.sin(wind_anger);
//綁定一個速度實例
this.vel = new Vector(wind_x, wind_y);
};
Drop對象的update方法
update方法負責,每一幀drop實例的屬性的改變 如位移的改變
Drop.prototype.update = function() {
this.prev = this.pos.copy();
//如果是有重力的情況,則縱向速度進行增加
if (OPTS.hasGravity) {
this.vel.y += gravity;
}
//
this.pos.add(this.vel);
};
Drop對象的draw方法
draw方法負責,每一幀drop實例的繪畫
Drop.prototype.draw = function() {
ctx.beginPath();
ctx.moveTo(this.pos.x, this.pos.y);
//目前只分為兩種情況,一種是rain 即貝塞爾曲線
if(OPTS.type =="rain"){
ctx.moveTo(this.prev.x, this.prev.y);
var ax = Math.abs(this.radius * Math.cos(wind_anger));
var ay = Math.abs(this.radius * Math.sin(wind_anger));
ctx.bezierCurveTo(this.pos.x + ax, this.pos.y + ay, this.prev.x + ax , this.prev.y + ay, this.pos.x, this.pos.y);
ctx.stroke();
//另一種是snow--即圓形
}else{
ctx.moveTo(this.pos.x, this.pos.y);
ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI*2);
ctx.fill();
}
};
bounce 下落落地反彈對象, 即上面雨水反彈的水滴, 你也可后期拓展為反彈的碎石片或者煙塵
定義的十分簡單,這里就不做詳細說明
var Bounce = function(x, y) {
var dist = Math.random() * 7;
var angle = Math.PI + Math.random() * Math.PI;
this.pos = new Vector(x, y);
this.radius = 0.2+ Math.random()*0.8;
this.vel = new Vector(
Math.cos(angle) * dist,
Math.sin(angle) * dist
);
};
Bounce.prototype.update = function() {
this.vel.y += gravity;
this.vel.x *= 0.95;
this.vel.y *= 0.95;
this.pos.add(this.vel);
};
Bounce.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, this.radius*DPR, 0, Math.PI * 2);
ctx.fill();
};
對外接口
update
即相當于整個canvas動畫的開始函數(shù)
function update() {
var d = new Date;
//清理畫圖
ctx.clearRect(0, 0, canvas.width, canvas.height);
var i = drops.length;
while (i--) {
var drop = drops[i];
drop.update();
//如果drop實例下降到底部,則需要在drops數(shù)組中清楚該實例對象
if (drop.pos.y >= canvas.height) {
//如果需要回彈,則在bouncess數(shù)組中加入bounce實例
if(OPTS.hasBounce){
var n = Math.round(4 + Math.random() * 4);
while (n--)
bounces.push(new Bounce(drop.pos.x, canvas.height));
}
//如果drop實例下降到底部,則需要在drops數(shù)組中清楚該實例對象
drops.splice(i, 1);
}
drop.draw();
}
//如果需要回彈
if(OPTS.hasBounce){
var i = bounces.length;
while (i--) {
var bounce = bounces[i];
bounce.update();
bounce.draw();
if (bounce.pos.y > canvas.height) bounces.splice(i, 1);
}
}
//每次產(chǎn)生的數(shù)量
if(drops.length < OPTS.maxNum){
if (Math.random() < drop_chance) {
var i = 0,
len = OPTS.numLevel;
for(; i<len; i++){
drops.push(new Drop());
}
}
}
//不斷循環(huán)update
requestAnimFrame(update);
}
init
init接口,初始化整個canvas畫布的一切基礎(chǔ)屬性 如獲得屏幕的像素比,和設(shè)置畫布的像素大小,和樣式的設(shè)置
function init(opts) {
OPTS = opts;
canvas = document.getElementById(opts.id);
ctx = canvas.getContext("2d");
////兼容高清屏幕,canvas畫布像素也要相應(yīng)改變
DPR = window.devicePixelRatio;
//canvas畫板像素大小, 需兼容高清屏幕,故畫板canvas長寬應(yīng)該乘于DPR
canvasWidth = canvas.clientWidth * DPR;
canvasHeight =canvas.clientHeight * DPR;
//設(shè)置畫板寬高
canvas.width = canvasWidth;
canvas.height = canvasHeight;
drop_chance = 0.4;
//設(shè)置樣式
setStyle();
}
function setStyle(){
if(OPTS.type =="rain"){
ctx.lineWidth = 1 * DPR;
ctx.strokeStyle = 'rgba(223,223,223,0.6)';
ctx.fillStyle = 'rgba(223,223,223,0.6)';
}else{
ctx.lineWidth = 2 * DPR;
ctx.strokeStyle = 'rgba(254,254,254,0.8)';
ctx.fillStyle = 'rgba(254,254,254,0.8)';
}
}
結(jié)束語
好了,一個簡單的drop組件已經(jīng)完成了,當然其存在著許多地方不夠完善,經(jīng)過本次drop組件的編寫,對于canvas的動畫實現(xiàn),我相信在H5的場景中擁有著許多可發(fā)掘的地方。
最后說下不足的地方和后期的工作哈:
0、該組件目前對外接口不夠多,可調(diào)節(jié)的范圍并不是很多,抽象不是很徹底
1、 setStyle 設(shè)置 基本樣式
2、 Drop 和Bounce 對象的 update 和 draw 方法的自定義,讓用戶可以設(shè)立更多下落的 速度和大小改變的形式和樣式效果
3、 應(yīng)增加對動畫的pause,加速和減速等操作的接口
以上所述是小編給大家介紹的JS和Canvas 實現(xiàn)下雨下雪效果的相關(guān)知識,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
本文轉(zhuǎn)載:http://blog.csdn.net/xllily_11/article/details/51444311
- 純JavaScript實現(xiàn)HTML5 Canvas六種特效濾鏡示例
- JavaScript+html5 canvas實現(xiàn)圖片破碎重組動畫特效
- 教你用幾十行js實現(xiàn)很炫的canvas交互特效
- js canvas實現(xiàn)星空連線背景特效
- js canvas實現(xiàn)隨機粒子特效
- javascript結(jié)合html5 canvas實現(xiàn)(可調(diào)畫筆顏色/粗細/橡皮)的涂鴉板
- Javascript保存網(wǎng)頁為圖片借助于html2canvas庫實現(xiàn)
- js+canvas實現(xiàn)滑動拼圖驗證碼功能
- JavaScript+html5 canvas實現(xiàn)本地截圖教程
- html5 canvas js(數(shù)字時鐘)實例代碼
- js和canvas繪制圓形金屬質(zhì)感特效
相關(guān)文章
bootstrap3 dialog 更強大、更靈活的模態(tài)框
這篇文章主要介紹了bootstrap3 dialog 更強大、更靈活的模態(tài)框,本文通過效果展示實例代碼詳解,需要的朋友可以參考下2017-04-04
Javascript數(shù)據(jù)結(jié)構(gòu)之棧和隊列詳解
要了解JavaScript數(shù)組的堆棧和隊列方法的操作,需要先對堆棧和隊列基礎(chǔ)知識有所了解,下面這篇文章主要給大家介紹了關(guān)于Javascript數(shù)據(jù)結(jié)構(gòu)之棧和隊列的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2022-05-05
使用JavaScript為Kindeditor自定義按鈕增加Audio標簽
這篇文章主要介紹了使用JavaScript為Kindeditor自定義按鈕增加Audio標簽的方法,KindEditor是一套開源的HTML可視化編輯器,需要的朋友可以參考下2016-03-03

