前端實現雪花效果,粒子特效
阿新 • • 發佈:2021-08-06
<template> <div id="main"> <canvas id="canvas" ref="canvas" style="z-index: 100;position: fixed;top: 0;width: 100%;height: 90%;"> 您的瀏覽器不支援 HTML5 canvas 標籤。 </canvas> </div> </template> <script> // import Footer from '@/components/Footer.vue'export default { components: { // Footer }, data() { return { //canvas init canvas: "", ctx: "", W: "", H: "", angle: 0, mp: 3000, particles: [], t:0, } }, mounted() { this._initCavas(); }, methods: { _initCavas() { this.canvas = document.getElementById("canvas"); this.ctx = this.canvas.getContext("2d"); //canvas dimensions this.W = window.innerWidth - 30; this.H = window.innerHeight - 10; this.canvas.width = this.W; this.canvas.height = this.H; //snowflake particles //雪花數量 this.mp = 500; this.particles = []; for (var i = 0; i < this.mp; i++) { this.particles.push({ x: Math.random() * this.W * 5, //x-coordinate y: Math.random() * this.H, //y-coordinate //改變大小 r: Math.random() * 1 + 1, //radius d: Math.random() * this.mp //density }) } clearInterval(localStorage.getItem('interval')); localStorage.setItem('interval', setInterval(this.draw, 25)); }, draw() { this.ctx.clearRect(0, 0, this.W, this.H); this.ctx.fillStyle = "rgba(37, 211, 236)"; this.ctx.fillStyle = "border: 1px solid rgb(37, 211, 236,0.2)"; this.ctx.fillStyle = "box-shadow: 0px 0px 3px rgb(37, 211, 236,0.5)"; this.ctx.beginPath(); for (var i = 0; i < this.mp; i++) { var p = this.particles[i]; this.ctx.moveTo(p.x, p.y); this.ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, true); } this.ctx.fill(); this.update(); }, update() { // this.angle += 0.01; for (var i = 0; i < this.mp; i++) { var p = this.particles[i]; p.y += Math.cos(this.angle + p.d) + 1 + p.r / 2; p.x += Math.sin(this.angle) * 2; if (p.x > this.W || p.x < 0 || p.y > this.H) { if (i % 3 > 0) { this.particles[i] = { x: Math.random() * this.W, y: -10, r: p.r, d: p.d }; } else { if (Math.sin(this.angle) > 0) { //Enter fromth this.particles[i] = { x: -5, y: Math.random() * this.H, r: p.r, d: p.d }; } else { this.particles[i] = { x: this.W + 5, y: Math.random() * this.H, r: p.r, d: p.d }; } } } } } } } </script> <style> #main { margin: 0; padding: 0; width: 100%; height: 100%; background: url(../../assets/img/aaaa.png); z-index: 999; background-repeat: no-repeat; position: absolute; background-size: 100% 100%; } </style>