原生js实现canvas群粒子动画效果
代码语言:html
所属分类:粒子
代码描述:原生js实现canvas群粒子动画效果
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> * { margin: 0; padding: 0; } canvas#canvas { display: block; background: #000; } </style> </head> <body translate="no"> <canvas id="canvas">Canvas not supported.</canvas> <script > (function () { 'use strict'; window.addEventListener('load', function () { var canvas = document.getElementById('canvas'); if (!canvas || !canvas.getContext) { return false; } /******************** Random Number ********************/ function rand(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } /******************** Var ********************/ // canvas var ctx = canvas.getContext('2d'); var X = canvas.width = window.innerWidth; var Y = canvas.height = window.innerHeight; var mouseX = X / 2; var mouseY = Y / 2; /******************** Animation ********************/ window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function (cb) { setTimeout(cb, 17); }; /******************** Pug ********************/ var pugNum = 500; var pugs = []; function Pug(ctx, x, y, h) { this.ctx = ctx; this.init(x, y, h); } Pug.prototype.init = function (x, y, h) { this.x = x; this.y = y; this.h = h; this.h === true ? this.r = 1 : this.r = 1; this.l = rand(5, 10); this.a = rand(0, 360); this.rad = this.a * Math.PI / 180; this.c = { r: rand(0, 255), g: rand(0, 100), b: rand(0, 255) }; this.v = { x: rand(-5, 5) * Math.random() + 1, y: rand(-5, 5) * Math.random() + 1, z: Math.random() * 3 }; }; Pug.prototype.draw = function () { var ctx = this.ctx; ctx.save(); ctx.globalCompositeOperation = 'lighter'; ctx.fillStyle = 'rgb(' + this.c.r + ', ' + this.c.g + ', ' + this.c.b + ')'; ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false); ctx.fill(); ctx.restore(); }; Pug.prototype.updatePosition = function () { this.x += Math.cos(this.rad) * 3 + this.v.x; this.y += Math.sin(this.rad) * 3 + this.v.y; }; Pug.prototype.wrapPosition = function () { if (this.x < 0 - 200) this.x = X; if (this.x > X + 200) this.x = 0; if (this.y < 0 - 200) this.y = Y; if (this.y > Y + 200) this.y = 0; }; Pug.prototype.closestPug = function (i) { var j = i; var dist = Number.MAX_VALUE; var closestI = 0; for (var i = 0; i < pugs.length; i++) { if (j !== i && pugs[i].h === true) { var x = Math.abs(this.x - pugs[i].x); var y = Math.abs(this.y - pugs[i].y); var d = x * x + y * y; .........完整代码请登录后点击上方下载按钮下载查看
网友评论0