canvas彩色圆点下落粒子动画效果代码
代码语言:html
所属分类:粒子
代码描述:canvas彩色圆点下落粒子动画效果代码
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> </head> <body translate="no"> <script > //////////////////////////////////////////////////////////////////////////////// "use strict"; console.clear(); requestAnimationFrame(main); function main() { const cont = document.body; const canvas = document.createElement('canvas'); const canvasSize = [0, 0]; canvas.style.display = 'block'; cont.style.margin = '0'; cont.appendChild(canvas); const canvasCtx = canvas.getContext('2d'); const state = createState(canvasSize); window.addEventListener('resize', () => onResize(canvasCtx, canvasSize, state)); onResize(canvasCtx, canvasSize, state); // precooling for (let i = 0; i < 10; ++i) process(state, canvasCtx, canvasSize, 1); let lastTime = Date.now() / 1000; const loop = () => { let time = Date.now() / 1000; let timeDelta = time - lastTime; if (timeDelta > 1) timeDelta = 1; lastTime = time; process(state, canvasCtx, canvasSize, timeDelta); render(state, canvasCtx, canvasSize, timeDelta); requestAnimationFrame(loop); }; requestAnimationFrame(loop); } function createState(canvasSize) { const state = { time: 0, stars: [], path: new Path2D() }; return state; } function process(state, canvasCtx, canvasSize, timeDelta) { state.time += timeDelta; const nStars = 256; while (state.stars.length < nStars) { state.stars.push(createStar(state, canvasSize)); } for (let i = 0; i < state.stars.length; ++i) { const star = state.stars[i]; star.isInPath = canvasCtx.isPointInPath(state.path, star.pos[0], star.pos[1]); const newPathFactor = star.isInPath ? 0.25 : 1; star.pathFactor = star.pathFactor * 0.95 + newPathFactor * 0.05; star.pos[0] += star.vel[0] * timeDelta * star.pathFactor; star.pos[1] += star.vel[1] * timeDelta * star.pathFactor; if (star.pos[1] > canvasSize[1] || star.pos[0] < 0 || star.pos[0] > canvasSize[0]) { state.stars.splice(i--, 1); continue; } } // for i } // process function render(state, canvasCtx, canvasSize, timeDelta) { canvasCtx.fillStyle = '#000000'; canvasCtx.fillRect(0, 0, canvasSize[0], canvasSize[1]); for (const star of state.stars) { drawStar(canvas.........完整代码请登录后点击上方下载按钮下载查看
网友评论0