<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>变换</title> </head> <body> <canvas id="mycanvas"></canvas> <script> function All(){ this.canvas = document.getElementById('mycanvas'); this.ctx = this.canvas.getContext('2d'); this.pr = window.devicePixelRatio || 1;//物理像素分辨率雨CSS像素分辨率的比值 this.windowW = document.documentElement.clientWidth;//屏幕宽 this.heightH = document.documentElement.clientHeight;//屏幕高 this.canvas.width = this.windowW * this.pr; this.canvas.height = this.heightH * this.pr; this.v = Math.cos;//余弦值 this.u = Math.PI * 2;//圆周率 this.z = Math.random;//随机数 this.ctx.scale(this.pr,this.pr); this.ctx.globalAlpha = 0.6;//设置透明度 this.q = []; this.f = 100; this.r = 0; this.init = function(){//初始化 this.logic(); } this.draws = function(i,j){ this.ctx.beginPath(); this.ctx.moveTo(i.x,i.y); this.ctx.lineTo(j.x,j.y); var k = j.x + (this.z() * 2 -.25) * this.f; n = this.count(j.y); this.ctx.lineTo(k,n); this.ctx.closePath(); this.r -= this.u / -50; this.ctx.fillStyle = '#' + (this.v(this.r) * 150 + 151 << 16 | this.v(this.r + this.u / 3) * 150 + 151 << 8 | this.v(this.r + this.u / 3 * 2) * 150 + 151).toString(16);//随机相似颜色 this.ctx.fill(); this.q[0] = this.q[1]; this.q[1] = {x: k, y: n}; } var self = this; this.logic = function(){ setInterval(function(){ self.ctx.clearRect(0,0,self.canvas.width,self.canvas.height); self.q = [{x:0, y:self.canvas.height*.7+self.f},{x:0, y:self.canvas.height*.7-self.f}]; while(self.q[1].x<self.canvas.width+self.f){ self.draws(self.q[0],self.q[1]) } },1000); //requestAnimationFrame(self.logic); } this.count = function(p){ var t = p + (this.z() * 2 - 1.1) * this.f; return (t > this.canvas.height || t < 0) ? this.count(p) : t; } } window.onload = function(){ var done = (new All).init(); } </script> </body> </html>
代码复制即可运行!代码看似简单,其实里面的算法并不简单每一步都需要认真的考虑清楚才能写的出来。