canvas实现米斯粒子箭头随机运动动画i效果代码
代码语言:html
所属分类:粒子
代码描述:canvas实现米斯粒子箭头随机运动动画i效果代码
代码标签: canvas 米斯 粒子 箭头 随机 运动 动画
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <style> html, body { padding: 0; margin: 0; overflow: hidden; } canvas { background: hsl(190, 25%, 7%); } </style> </head> <body> <script > "use strict"; const NUM_MICE = 100; class Agent { constructor(type, pos, boundingBox) { this.type = type; this.pos = pos; this.boundingBox = boundingBox; } } class Mouse extends Agent { constructor(pos, boundingBox) { super('mouse', pos, boundingBox); this.color = `hsl(0, 0%, ${Math.random() * 100}%)`; this.target = pos; this.angle = 0; this.rotationSpeed = Math.random() * 0.5; // rotation speed in radians this.speed = Math.random() * 0.1; // speed of moving towards the target } update() { const distance = Math.hypot(this.target.x - this.pos.x, this.target.y - this.pos.y); if (distance < 1) { // new random target location this.target = { x: Math.random() * window.innerWidth, y: Math.random() * window.innerHeight }; } else { // move to target with easing const dx = this.target.x - this.pos.x; const dy = this.target.y - this.pos.y; // calculate the desired angle of rotation const desiredAngle = Math.atan2(dy, dx); // calculate the difference in current angle and the desired angle let diff = desiredAngle - this.angle; // normalize it to (-PI, PI) diff = ((diff + Math.PI) % (Math.PI * 2)) - Math.PI; // calculate the new angle by adding a fraction of the difference to the old angle this.angle += diff * this.rotationSpeed; // Only move when the difference in angle is small enough (say, less than 5 degrees) if (Math.abs(diff) < Math.PI / 36) { this.pos.x += dx * this.speed; this.pos.y += dy * this.speed; .........完整代码请登录后点击上方下载按钮下载查看
网友评论0