javascript canvas實(shí)現(xiàn)雨滴效果
本文實(shí)例為大家分享了javascript canvas實(shí)現(xiàn)雨滴效果的具體代碼,供大家參考,具體內(nèi)容如下
先看效果
看起來很炫酷,其實(shí)就是實(shí)現(xiàn)了雨滴的掉落還有最后的圓
還是看源碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { margin: 0; padding: 0; } body { background-color: #000; } </style> </head> <body> <canvas></canvas> <script> // 獲取畫布 var canvas = document.querySelector('canvas') // 獲取畫筆 var ctx = canvas.getContext('2d') // 不能用css改變畫布大小 var ch = canvas.height = window.innerHeight var cw = canvas.width = window.innerWidth // 放雨滴 var arrRain = [] // 監(jiān)聽屏幕大小,屏幕發(fā)生變化讓畫布也跟著改變大小 window.onresize = function () { ch = canvas.height = window.innerHeight cw = canvas.width = window.innerWidth } // 獲取一個(gè)隨機(jī)數(shù),目的是為了生成隨機(jī)雨滴 function randow(min, max) { return Math.random() * (max - min) + min } // 構(gòu)造函數(shù) function Rain() { } // 為rain添加屬性和方法 Rain.prototype = { // 初始化位置和雨滴下落的圓的半徑 init: function () { this.x = randow(0, cw) this.y = 0 // 雨滴最終落地的距離不能超出屏幕 this.h = randow(0.8 * ch, 0.9 * ch) this.r = 1 // 開始圓的半徑 this.vr = 1 // 半徑增長(zhǎng)的速度 this.vy = randow(4, 5) }, // 畫方法 draw: function () { // 小于h的時(shí)候,畫雨滴,畫矩形 if (this.y < this.h) { ctx.beginPath() ctx.fillStyle = 'white' ctx.fillRect(this.x, this.y, 4, 10) } else { // 畫圓 ctx.beginPath() ctx.strokeStyle = 'white' ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI) ctx.stroke() } }, // 雨滴移動(dòng) move: function () { // 小于h時(shí),加y實(shí)現(xiàn)雨滴移動(dòng) if (this.y < this.h) { this.y += this.vy } else { // 實(shí)現(xiàn)水花四濺的效果 if (this.r < 70) { this.r += this.vr } else { // 結(jié)束效果之后初始化,又從天上生成雨滴,所以要調(diào)用init函數(shù) this.init() } } this.draw() } } // 生成雨滴 function createRain(num) { for (var i = 0; i < num; i++) { // 隨機(jī)生成雨滴,不是同時(shí)生成 setTimeout(function () { var rain = new Rain() rain.init() rain.draw() arrRain.push(rain) }, 300 * i) } } createRain(60) setInterval(function () { ctx.beginPath() ctx.fillStyle = 'rgba(0,0,0,0.05)' ctx.fillRect(0, 0, cw, ch) for (var k of arrRain) { k.move() } }, 1000 / 80) </script> </body> </html>
這些也就是雨滴實(shí)現(xiàn)的源碼,僅供參考。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
風(fēng)吟的小型JavaScirpt庫 (FY.JS).
此庫非常的迷你壓縮之后只有1.54KB.但是卻有類似jquery的語法有COOKIE操作還有DOM以及AJAX跟綁定事件函數(shù).2010-03-03基于ajax與msmq技術(shù)的消息推送功能實(shí)現(xiàn)代碼
這篇文章主要介紹了基于ajax與msmq技術(shù)的消息推送功能實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,有興趣的可以了解一下。2016-12-12Bootstrap的aria-label和aria-labelledby屬性實(shí)例詳解
這篇文章主要介紹了Bootstrap的aria-label和aria-labelledby屬性實(shí)例詳解,需要的朋友可以參考下2018-11-11Js注冊(cè)協(xié)議倒計(jì)時(shí)的小例子
Js注冊(cè)協(xié)議倒計(jì)時(shí)的小例子,需要的朋友可以參考一下2013-06-06jquery的.click()點(diǎn)擊事件為什么無效,on('click',function())如何使
jquery的.click()點(diǎn)擊事件,通常都是可以正常使用的,有時(shí)選中的選擇器被點(diǎn)擊時(shí)無法觸發(fā)回調(diào)函數(shù),這是為什么呢?改成on綁定click就可以了嗎?面對(duì)這樣的情況,on('click',function())應(yīng)該如何使用?2023-08-08