您好,登錄后才能下訂單哦!
本文實(shí)例講述了原生JS實(shí)現(xiàn)的雪花飄落動(dòng)畫效果。分享給大家供大家參考,具體如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>www.jb51.net JS下雪動(dòng)畫</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <style> .masthead { background-color:#333; display:block; width:100%; height:400px; } </style> <body> <div class="masthead"></div> <script> (function () { var COUNT = 300; var masthead = document.querySelector('.masthead'); var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var width = masthead.clientWidth; var height = masthead.clientHeight; var i = 0; var active = false; function onResize() { width = masthead.clientWidth; height = masthead.clientHeight; canvas.width = width; canvas.height = height; ctx.fillStyle = '#FFF'; var wasActive = active; active = width > 600; if (!wasActive && active) requestAnimFrame(update); } var Snowflake = function () { this.x = 0; this.y = 0; this.vy = 0; this.vx = 0; this.r = 0; this.reset(); }; Snowflake.prototype.reset = function() { this.x = Math.random() * width; this.y = Math.random() * -height; this.vy = 1 + Math.random() * 3; this.vx = 0.5 - Math.random(); this.r = 1 + Math.random() * 2; this.o = 0.5 + Math.random() * 0.5; }; canvas.style.position = 'absolute'; canvas.style.left = canvas.style.top = '0'; var snowflakes = [], snowflake; for (i = 0; i < COUNT; i++) { snowflake = new Snowflake(); snowflakes.push(snowflake); } function update() { ctx.clearRect(0, 0, width, height); if (!active) return; for (i = 0; i < COUNT; i++) { snowflake = snowflakes[i]; snowflake.y += snowflake.vy; snowflake.x += snowflake.vx; ctx.globalAlpha = snowflake.o; ctx.beginPath(); ctx.arc(snowflake.x, snowflake.y, snowflake.r, 0, Math.PI * 2, false); ctx.closePath(); ctx.fill(); if (snowflake.y > height) { snowflake.reset(); } } requestAnimFrame(update); } // shim layer with setTimeout fallback window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })(); onResize(); window.addEventListener('resize', onResize, false); masthead.appendChild(canvas); })(); </script></body></html>
使用本站HTML/CSS/JS在線運(yùn)行測試工具:http://tools.jb51.net/code/HtmlJsRun,可得到如下測試運(yùn)行效果:
更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript動(dòng)畫特效與技巧匯總》、《JavaScript頁面元素操作技巧總結(jié)》、《JavaScript運(yùn)動(dòng)效果與技巧匯總》、《JavaScript圖形繪制技巧總結(jié)》、《JavaScript切換特效與技巧總結(jié)》、《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計(jì)有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。