canvas树木生长动画效果代码
代码语言:html
所属分类:动画
代码描述:canvas树木生长动画效果代码
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> body { margin: 0; overflow: hidden;}canvas { position: absolute; background: linear-gradient( to bottom, rgba(73,192,240,1) 0%, rgba(168,231,255,1) 100% );}#menu { position: absolute; display: flex; flex-direction: column; padding: 10px;}button, label { font-family: Monospace; background: transparent; border: 1px solid #512fff; color: #512fff; font-size: 20px; cursor: pointer; margin: 10px 0;}label { border: none;} </style> </head> <body> <canvas></canvas> <div id="menu"><button onclick="init()">Restart</button><label><input type="checkbox" id="leaves" checked="checked" /><span>Draw leaves</span></label></div> <script > const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); const branches = []; const leaves = []; const trunkHeight = 170; let hues = [70, 20]; let hueIndex = 0; let currentHue = hues[0]; let drawLeaves; let animFrame; class Branch { constructor(x, y, length, angle, speed, width) { this.x = x; this.y = y; this.curLength = 0; this.length = length; this.angle = angle; this.interpolant = 0; this.speed = speed; this.width = Math.max(width, 2); this.done = false; this.lengthLimit = 40 + Math.random() * 30; } draw() { ctx.save(); ctx.translate(this.x, this.y); ctx.rotate(this.angle + Math.PI); ctx.beginPath(); // Set Y to -3 to hide most of the visible gaps between branches ctx.moveTo(0, -3); ctx.lineTo(0, this.interpolant * this.length); ctx.closePath(); ctx.lineWidth = this.width; ctx.stroke(); ctx.restore(); } update() { if (!this.done) { const x = this.x + Math.sin(this.angle) * this.interpolant * this.length; const y = this.y - Math.cos(this.angle) * this.interpolant * this.length; if (this.interpolant < 1) { this.interpolant += this.speed; // Add leaves only to smaller branches at random intervals if (drawLeaves && this.length < 120 && Math.random() > 0.85) { leaves.push(new Leaf(x, y)); } } // Branch has reached it's target length else { // Create new branches only if branch is long enough if (this.length >= this.lengthLimit) { const amount = 2 + Math.floor(Math.random() * 2); // Create new branches. I decided to use random angles to add more variety, // but that makes it possible for branches to go in the same direction... for (let i = 0; i < amount; i++) { branc.........完整代码请登录后点击上方下载按钮下载查看
网友评论0