html canvas粒子线条组合动画背景特效
生活随笔
收集整理的這篇文章主要介紹了
html canvas粒子线条组合动画背景特效
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
代碼如下:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body> <canvas id="cas" width="840" height="945"></canvas><script>var canvas = document.getElementById("cas");var ctx = canvas.getContext("2d");resize();window.onresize = resize;function resize() {canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;}var RAF = (function() {return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {window.setTimeout(callback, 1000 / 60);};})();// 鼠標(biāo)活動(dòng)時(shí),獲取鼠標(biāo)坐標(biāo)var warea = {x: null, y: null, max: 20000};window.onmousemove = function(e) {e = e || window.event;warea.x = e.clientX;warea.y = e.clientY;};window.onmouseout = function(e) {warea.x = null;warea.y = null;};// 添加粒子// x,y為粒子坐標(biāo),xa, ya為粒子xy軸加速度,max為連線的最大距離var dots = [];for (var i = 0; i < 300; i++) {var x = Math.random() * canvas.width;var y = Math.random() * canvas.height;var xa = Math.random() * 2 - 1;var ya = Math.random() * 2 - 1;dots.push({x: x,y: y,xa: xa,ya: ya,max: 6000})}// 延遲100秒開始執(zhí)行動(dòng)畫,如果立即執(zhí)行有時(shí)位置計(jì)算會(huì)出錯(cuò)setTimeout(function() {animate();}, 100);// 每一幀循環(huán)的邏輯function animate() {ctx.clearRect(0, 0, canvas.width, canvas.height);// 將鼠標(biāo)坐標(biāo)添加進(jìn)去,產(chǎn)生一個(gè)用于比對(duì)距離的點(diǎn)數(shù)組var ndots = [warea].concat(dots);dots.forEach(function(dot) {// 粒子位移dot.x += dot.xa;dot.y += dot.ya;// 遇到邊界將加速度反向dot.xa *= (dot.x > canvas.width || dot.x < 0) ? -1 : 1;dot.ya *= (dot.y > canvas.height || dot.y < 0) ? -1 : 1;// 繪制點(diǎn)ctx.fillRect(dot.x - 0.5, dot.y - 0.5, 1, 1);// 循環(huán)比對(duì)粒子間的距離for (var i = 0; i < ndots.length; i++) {var d2 = ndots[i];if (dot === d2 || d2.x === null || d2.y === null) continue;var xc = dot.x - d2.x;var yc = dot.y - d2.y;// 兩個(gè)粒子之間的距離var dis = xc * xc + yc * yc;// 距離比var ratio;// 如果兩個(gè)粒子之間的距離小于粒子對(duì)象的max值,則在兩個(gè)粒子間畫線if (dis < d2.max) {// 如果是鼠標(biāo),則讓粒子向鼠標(biāo)的位置移動(dòng)if (d2 === warea && dis > (d2.max / 2)) {dot.x -= xc * 0.03;dot.y -= yc * 0.03;}// 計(jì)算距離比ratio = (d2.max - dis) / d2.max;// 畫線ctx.beginPath();ctx.lineWidth = ratio / 2;//線條顏色ctx.strokeStyle = 'rgba(0,0,0,' + (ratio + 0.2) + ')';ctx.moveTo(dot.x, dot.y);ctx.lineTo(d2.x, d2.y);ctx.stroke();}}// 將已經(jīng)計(jì)算過的粒子從數(shù)組中刪除ndots.splice(ndots.indexOf(dot), 1);});RAF(animate);} </script></body> </html>效果如下:
?
總結(jié)
以上是生活随笔為你收集整理的html canvas粒子线条组合动画背景特效的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端基础——URL详解
- 下一篇: python弧度值转角度值_python