原生JS實現煙花效果
阿新 • • 發佈:2020-03-12
原生JS實現煙花效果,點選頁面生成煙花,向四周擴散,然後再墜落下去。(這裡的煙花我是用的特殊字元愛心形狀)
基礎css程式碼
/* 設定基礎的css樣式 */ body{background: #000;overflow: hidden;} .fire{position: absolute;width: 4px;height: 30px;}
js程式碼:
1、給頁面新增點選事件,生成主體煙花
//給頁面設定點選事件 document.onclick = function(eve){ var e = eve || window.event; //設定一個空陣列,用來後面存放小煙花 var arr = []; //獲取滑鼠點選的位置 var x = e.clientX; var y = e.clientY; //設定步長 var speed = 20; //生成大煙花,設定他的css樣式,出發點在可視區頁面的下方 var fire = document.createElement('div'); fire.className = 'fire'; fire.style.background = randomColor(); fire.style.left = x + 'px'; fire.style.top = document.documentElement.clientHeight+'px'; //將大煙花追加到頁面上 document.body.appendChild(fire);
2、設定定時器,讓煙花向上運動,刪除
//生成定時器 var t = setInterval(function(){ //判斷如果大煙花的TOP值小於小於目標值,清除定時器,並且將大煙花清除 if(fire.offsetTop <= y){ clearInterval(t); document.body.removeChild(fire); //執行show(生成小煙花) show(); } //讓大煙花垂直向上運動 fire.style.top = fire.offsetTop - speed +'px'; },30);
3、然後在點選的位置生成小煙花,設定樣式
function show(){ //利用迴圈,生成50個小煙花,給小煙花新增css屬性 for(var i=0;i<50;i++){ var sFire = document.createElement('div'); // sFire.className = 'small-fire'; sFire.style.left = x +'px'; sFire.style.top = y +'px'; // sFire.style.background = randomColor(); sFire.style.color = randomColor(); sFire.innerHTML = '❤'; sFire.style.position = 'absolute'; //生成隨機數 var a=Math.random()*360; sFire.sx = Math.sin(a*180/Math.PI)*20*Math.random(); sFire.sy = Math.cos(a*180/Math.PI)*20*Math.random(); //將小煙花追加到頁面上 document.body.appendChild(sFire); //將生成的煙花資訊都新增到陣列中 arr.push(sFire); } }
4、設定定時器,讓小煙花完成自由落體運動
setInterval(function move(){ //利用迴圈一直改變小煙花的位置 for(var i=0;i<arr.length;i++){ //設定將每次迴圈的第i個小煙花的運動範圍 arr[i].style.left = arr[i].offsetLeft + arr[i].sx + 'px'; arr[i].style.top = arr[i].offsetTop + arr[i].sy + 'px'; //讓煙花垂直方向的位置每次都增加,實現下落效果 arr[i].sy += 1; //判斷煙花是否運動出螢幕可視區,如果是,就將它刪除 if(arr[i].offsetLeft<0 || arr[i].offsetLeft > document.documentElement.clientWidth || arr[i].offsetTop > document.documentElement.clientHeight){ document.body.removeChild(arr[i]); // arr.splice(i,1); } } },30) }
5、最後別忘了我們的隨機數和隨機顏色的封裝
// 範圍隨機數 function random(max,min){ return Math.round(Math.random()*(max-min)+min); } // 隨機顏色 function randomColor(){ return "rgb("+random(0,255)+","+random(0,255)+")"; }
最後我們的煙花效果就實現了
今天的分享就到這裡,希望大家能夠喜歡。
更多JavaScript精彩特效分享給大家:
Javascript選單特效大全
javascript仿QQ特效彙總
JavaScript時鐘特效彙總
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。