JavaScript canvas實現跟隨滑鼠事件
阿新 • • 發佈:2020-02-11
本文例項為大家分享了用canvas實現跟隨滑鼠事件的具體程式碼,供大家參考,具體內容如下
//滑鼠移動 展現光片
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> body { margin: 0; overflow: hidden; } #canvas { background: #000; } </style> </head> <body> <canvas id="canvas"></canvas> <script> var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var circleList = []; canvas.width = window.innerWidth; canvas.height = window.innerHeight; canvas.addEventListener('mousemove',function (e) { // 將物件push到陣列中,畫出來的彩色小點可以看作每一個物件中記錄著資訊 然後存在陣列中 circleList.push(new Circle(e.clientX,e.clientY)); }) //取x到y之間隨機數:Math.round(Math.random()*(y-x)+x) 包括y function random(min,max) { return Math.round(Math.random() * (max - min) + min); } function Circle(x,y) { this.x = x; this.y = y; this.vx = (Math.random() - 0.5) * 3; //隨機出來一個正數,或者負數。乘3是為了讓速度變得大一點 this.vy = (Math.random() - 0.5) * 3; this.color = 'rgb(' + random(0,255) + ',' + random(0,255) + ')'; this.a = 1; // 初始透明度 this.draw(); } Circle.prototype = { draw() { context.beginPath(); context.fillStyle = this.color; context.globalCompositeOperation = 'lighter'; context.globalAlpha = this.a; //全域性透明度 context.arc(this.x,this.y,30,Math.PI * 2,false); context.fill(); this.update(); },update() { // 根據速度更新每一個小圓的位置 this.x += this.vx; this.y += this.vy; this.a *= 0.98; } } function render() { //把原來的內容區域清除掉 context.clearRect(0,canvas.width,canvas.height); circleList.forEach(function (ele,i) { ele.draw(); if (ele.a < 0.05) { circleList.splice(i,1); } }); requestAnimationFrame(render); //動畫,會根據瀏覽器的重新整理頻率更新動畫 } render(); </script> </body> </html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。