使用JS實現(xiàn)簡單噴泉效果,最近,在教學(xué)生使用JS的基本操作,為了練習(xí)JS的基本作用,特地寫了一個噴泉效果,代碼如下: 頁面代碼: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="js/particle.js" type="text/javascript" charset="utf-8"></script> <style type="text/css"> body{ margin: 0px; } </style> </head> <body> </body> </html> Particle.js代碼如下: window.onload = function(){ // 創(chuàng)建一個畫布對象 var canvas = document.createElement("canvas"); // 設(shè)置大小和顏色 canvas.width = window.innerWidth; canvas.height = window.innerHeight; canvas.style.backgroundColor = "#333333"; // 將畫布放置到body里 document.body.appendChild(canvas); // 得到畫筆 var context = canvas.getContext("2d"); // 定義一個存放所有粒子的數(shù)組 var particles = [ ]; // 調(diào)用顯示粒子 showParticle(); // 創(chuàng)建并顯示粒子的方法 function showParticle(){ // 循環(huán)操作 setInterval(function(){ // 清空畫布 context.clearRect(0,0,canvas.width, canvas.height); // 創(chuàng)建粒子 var p = new Particle(canvas.width * 0.5, canvas.height * 0.5); // 將粒子裝入存放粒子的數(shù)組 particles.push(p); // 循環(huán)更新所有粒子的位置 for (var i = 0;i<particles.length;i++) { // 更新位置 particles[i].updateData(); } }, 50); } function Particle(x, y){ // 原坐標(biāo) this.x = x; this.y = y; // 初始出現(xiàn)的改變的y的值 this.yVal = -5; // 改變的x的值 this.xVal = Math.random() * 8 - 4; // 定義一個下降的重力加速度 this.g = 0.1; // 更新位置 this.updateData = function(){ // X值的變化 this.x = this.x + this.xVal; // Y值的變化 this.y = this.y + this.yVal; // 每次改變Y值速度的變化 this.yVal = this.yVal + this.g; // 生成一個隨機顏色 context.fillStyle = "#" + Math.floor(Math.random() * 0xffffff).toString(16); // 將更新位置后的圓繪制出來 this.draw(); }; // 繪圖的方法 this.draw = function(){ // 開始畫圖 context.beginPath(); // 畫圓 context.arc(this.x, this.y,5,0,Math.PI * 2, false); // 結(jié)束畫圖 context.closePath(); // 填充 context.fill(); }; } }; |
|