JS+Canvas 實現下雨下雪效果,jscanvas

來源:互聯網
上載者:User

JS+Canvas 實現下雨下雪效果,jscanvas

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

展示:

下雨 下雪

看起來效果還是不錯的,相對於使用建立dom元素來製作多物體位移動畫, 使用canvas會更加容易快捷,以及效能會更好

調用代碼

<!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 snowspeed : [0.4,2.5], //速度範圍size_range: [0.5,1.5],//大小半徑範圍hasBounce: true, //是否有反彈效果or false,wind_direction: -105 //角度hasGravity: true //是否有重力考慮});</script></body></html>

好了,接下來講解一下簡單的實現原理 首先,先定義一些我們會用到的全域變數,如風向角度,幾率,對象資料等

定義全域變數

//定義兩個對象資料//分別是drops下落物體對象//和反彈物體bounces對象var drops = [], bounces = [];//這裡設定重力加速度為0.2/一幀var gravity = 0.2;var speed_x_x, //橫向加速度speed_x_y, //縱向加速度wind_anger; //風向//畫布的像素寬高var canvasWidth,canvasHeight;//建立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 ,縱向速度ythis.x = x || 0;this.y = y || 0;};//公有方法- add : 速度改變函數,根據參數對速度進行增加//由於業務需求,考慮的都是下落加速的情況,故沒有減速的,後期可拓展/** @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 : 複製一個vector,來用作儲存之前速度節點的記錄Vector.prototype.copy = function() {//返回一個同等速度屬性的Vector執行個體return new Vector(this.x, this.y);};Drop 下落物體對象, 即上面效果中的雨滴和雪, 在後面你也可自己拓展為隕石或者炮彈對於Drop對象其基本定義如下//建構函式var Drop = function() {/* .... */};//公有方法-update Drop.prototype.update = function() {/* .... */};//公有方法-drawDrop.prototype.draw = function() {/* .... */};

看了上面的三個方法,是否都猜到他們的作用呢,接下來讓我們瞭解這三個方法做了些什麼

建構函式

建構函式主要負責定義drop對象的初始資訊,如速度,初始座標,大小,加速度等

//建構函式 Dropvar Drop = function() {//隨機設定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);}//設定下落元素的大小//通過調用的OPTS函數的半徑範圍進行隨機取值this.radius = (OPTS.size_range[0] + Math.random() * OPTS.size_range[1]) *DPR;//獲得drop初始速度//通過調用的OPTS函數的速度範圍進行隨機取值this.speed = (OPTS.speed[0] + Math.random() * OPTS.speed[1]) *DPR;this.prev = this.pos;//將角度乘以 0.017453293 (2PI/360)即可轉換為弧度。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動畫的開始函數

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數組中清楚該執行個體對象if (drop.pos.y >= canvas.height) {//如果需要回彈,則在bouncess數組中加入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數組中清楚該執行個體對象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);}}//每次產生的數量if(drops.length < OPTS.maxNum){if (Math.random() < drop_chance) {var i = 0,len = OPTS.numLevel;for(; i<len; i++){drops.push(new Drop());}}}//不斷迴圈updaterequestAnimFrame(update);}

init

init介面,初始化整個canvas畫布的一切基礎屬性 如獲得螢幕的像素比,和設定畫布的像素大小,和樣式的設定

function init(opts) {OPTS = opts;canvas = document.getElementById(opts.id);ctx = canvas.getContext("2d");////相容高清螢幕,canvas畫布像素也要相應改變DPR = window.devicePixelRatio;//canvas畫板像素大小, 需相容高清螢幕,故畫板canvas長寬應該乘於DPRcanvasWidth = canvas.clientWidth * DPR;canvasHeight =canvas.clientHeight * DPR;//設定畫板寬高canvas.width = canvasWidth;canvas.height = canvasHeight;drop_chance = 0.4;//設定樣式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)';}}

結束語

好了,一個簡單的drop組件已經完成了,當然其存在著許多地方不夠完善,經過本次drop組件的編寫,對於canvas的動畫實現,我相信在H5的情境中擁有著許多可發掘的地方。

最後說下不足的地方和後期的工作哈:

0、該組件目前對外介面不夠多,可調節的範圍並不是很多,抽象不是很徹底

1、 setStyle 設定 基本樣式

2、 Drop 和Bounce 對象的 update 和 draw 方法的自訂,讓使用者可以設立更多下落的 速度和大小改變的形式和樣式效果

3、 應增加對動畫的pause,加速和減速等操作的介面

以上所述是小編給大家介紹的JS和Canvas 實現下雨下雪效果的相關知識,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!

本文轉載:http://blog.csdn.net/xllily_11/article/details/51444311

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.