JavaScript canvas實現跟隨滑鼠移動小球
阿新 • • 發佈:2021-02-18
本文例項為大家分享了js跟隨滑鼠移動小球的具體程式碼,供大家參考,具體內容如下
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> canvas{ border: 1px solid #000; } </style> </head> <body> <canvas id="mycanvas" width="1500" height="800"></canvas> <script> // 建立畫布 var canvas = document.getElementById('mycanvas'); var ctx = canvas.getContext('2d'); // 球類 function Ball(x,y) { this.x = x; this.y = y; // 初始半徑 this.r = parseInt(Math.random() * 50) + 10; this.step = parseInt(Math.random() * 5) + 0.1; // 設定隨機顏色 this.color = getRandom(); // 設定隨機方向 this.dx = parseInt(Math.random() * 10) - 5; this.dy = parseInt(Math.random() * 10) - 5; // 將自身物件裝入陣列中 ballArr.push(this); } // 在陣列中刪除物件 Ball.prototype.remove = function() { for (var i = 0; i < ballArr.length; i++) { if (ballArr[i] == this) { ballArr.splice(i,1); } } } // 更新資料 Ball.prototype.update = function() { // 更新資料 this.x += this.dx; this.y += this.dy; this.r -= this.step; // 清除陣列中的小球 if (this.r <= 0) { this.remove(); } // 如果超出邊界,小球繼續運動 if (this.x < 0) { this.x = 1500; this.color = getRandom(); } else if (this.x > 1500) { this.x = 0; this.color = getRandom(); } else if (this.y < 0) { this.y = 800; this.color = getRandom(); } else if (this.y > 800) { this.y = 0; this.color = getRandom(); } } // 渲染小球 Ball.prototype.render = function() { ctx.beginPath(); ctx.arc(this.x,this.y,this.r,Math.PI * 2,false); ctx.fillStyle = this.color; ctx.fill(); } // canvas 畫布DOM2事件 canvas.addEventListener("mousemove",function(event) { new Ball(event.offsetX,event.offsetY); }); var ballArr = []; // 定時器進行動畫渲染和更新 setInterval(function() { // 動畫邏輯 // 清屏-更新-渲染 ctx.clearRect(0,canvas.width,canvas.height); // 小球的更新和渲染 for (var i = 0; i < ballArr.length; i++) { ballArr[i].update(); if (ballArr[i]) { ballArr[i].render(); } } },30); // 隨機顏色 function getRandom() { var allType = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f"; var allTypeArr = allType.split(","); var color = "#"; // 拼接顏色字串 for (var i = 0; i < 6; i++) { var random = parseInt(Math.random() * allTypeArr.length); color += allTypeArr[random]; } return color; } </script> </body> </html>
效果
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。