這篇文章主要講解了原生js canvas實(shí)現(xiàn)鼠標(biāo)跟隨效果的方法,內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會有幫助。
效果展示:
源碼展示:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>canvas鼠標(biāo)跟隨效果(原生js實(shí)現(xiàn))</title> <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script> <style> * { margin:0; padding:0; } body { overflow:hidden; } #myCanvas { background-color:#000; } </style> </head> <body> <canvas id="myCanvas"></canvas> <script> var myCanvas = document.getElementById('myCanvas'); var ctx = myCanvas.getContext("2d"); var starlist = []; function init() { // 設(shè)置canvas區(qū)域的范圍為整個(gè)頁面 myCanvas.width = window.innerWidth; myCanvas.height = window.innerHeight; }; init(); // 監(jiān)聽屏幕大小改變 重新為canvas大小賦值 window.onresize = init; // 當(dāng)鼠標(biāo)移動時(shí) 將鼠標(biāo)坐標(biāo)傳入構(gòu)造函數(shù) 同時(shí)創(chuàng)建一個(gè)對象 myCanvas.addEventListener('mousemove', function(e) { // 將對象push到數(shù)組中,畫出來的彩色小點(diǎn)可以看作每一個(gè)對象中記錄著信息 然后存在數(shù)組中 starlist.push(new Star(e.offsetX, e.offsetY)); }); // 隨機(jī)數(shù)函數(shù) function random(min, max) { // 設(shè)置生成隨機(jī)數(shù)公式 return Math.floor((max - min) * Math.random() + min); }; // 構(gòu)造函數(shù) function Star(x, y) { // 將坐標(biāo)存在每一個(gè)點(diǎn)的對象中 this.x = x; this.y = y; // 設(shè)置隨機(jī)偏移量 this.vx = (Math.random() - 0.5) * 3; this.vy = (Math.random() - 0.5) * 3; this.color = 'rgb(' + random(0, 256) + ',' + random(0, 256) + ',' + random(0, 256) + ')'; // 初始透明度 this.a = 1; // 開始畫 this.draw(); } // 再star對象原型上封裝方法 Star.prototype = { // canvas根據(jù)數(shù)組中存在的每一個(gè)對象的小點(diǎn)信息開始畫 draw: function() { ctx.beginPath(); ctx.fillStyle = this.color; // 圖像覆蓋 顯示方式 lighter 會將覆蓋部分的顏色重疊顯示出來 ctx.globalCompositeOperation = 'lighter' ctx.globalAlpha = this.a; ctx.arc(this.x, this.y, 30, 0, Math.PI * 2, false); ctx.fill(); this.updata(); }, updata: function() { // 根據(jù)偏移量更新每一個(gè)小點(diǎn)的位置 this.x += this.vx; this.y += this.vy; // 透明度越來越小 this.a *= 0.98; } } // 渲染 function render() { // 每一次根據(jù)改變后數(shù)組中的元素進(jìn)行畫圓圈 把原來的內(nèi)容區(qū)域清除掉 ctx.clearRect(0, 0, myCanvas.width, myCanvas.height) // 根據(jù)存在數(shù)組中的每一位對象中的信息畫圓 starlist.forEach(function(ele, i) { ele.draw(); // 如果數(shù)組中存在透明度小的對象 ,給他去掉 效果展示逐漸消失 if (ele.a < 0.05) { starlist.splice(i, 1); } }); requestAnimationFrame(render); } render(); </script> <pre > 感: 最近貢獻(xiàn)一下我在教學(xué)中的小案例可以能給你一些幫助 ,希望繼續(xù)關(guān)注我的博客 --王 </pre> </body> </html>
網(wǎng)站名稱:原生jscanvas實(shí)現(xiàn)鼠標(biāo)跟隨效果的方法-創(chuàng)新互聯(lián)
文章位置:http://chinadenli.net/article2/deegic.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導(dǎo)航、移動網(wǎng)站建設(shè)、網(wǎng)站制作、建站公司、手機(jī)網(wǎng)站建設(shè)、營銷型網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)