模拟电火花动画效果
代码语言:html
所属分类:动画
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> body { width: 100vw; height: 100vh; background: #222222; display: flex; justify-content: center; align-items: center; } </style> </head> <body translate="no"> <canvas id="canvas"></canvas> <script > const leftCircleRadius = 25; const rightCircleRadius = 25; const borderSpacing = 5; const lineCount = 5; const lineWidth = 2; const lineStep = 10; const freq = 2.0; const ampl = 50.0; const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); function setSize() { const s = Math.min(window.innerWidth, window.innerHeight); canvas.width = 3 * s / 4; canvas.height = 3 * s / 4; } function translateRotation(center_x, center_y, radius, angle) { const x = center_x + Math.cos(angle * Math.PI / 180) * radius; const y = center_y + Math.sin(angle * Math.PI / 180) * radius; return { x: x, y: y }; } function distance(p1x, p1y, p2x, p2y) { const dx = p2x - p1x; const dy = p2y - p1y; return Math.sqrt(dx * dx + dy * dy); } function calcVertical(p1x, p1y, p2x, p2y, lineWidth) { const dx = p2x - p1x; const dy = p2y - p1y; const length = distance(p1x, p1y, p2x, p2y); const pv1x = p1x - lineWidth / 2 / length * dy; const pv1y = p1y + lineWidth / 2 / length * dx; const pv2x = p1x + lineWidth / 2 / length * dy; const pv2y = p1y - lineWidth / 2 / length * dx; return { pv1x, pv1y, pv2x, pv2y }; } const clampNumber = (num, a = 0, b = 1) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); function draw() { const halfHeight = canvas.height / 2; const leftCircleCenterX = borderSpacing + leftCircleRadius; const leftCircleCenterY = halfHeight; const rightCircleCenterX = canvas.width - borderSpacing - rightCircleRadius; const rightCircleCenterY = halfHeight; const lineStart = translateRotation(leftCircleCenterX, leftCircleCenterY, leftCircleRadius, 360 - 45); const lineEnd = translateRotation(rightCircleCenterX, rightCircleCenterY, rightCircleRadius, 180 + 45); const lineSegments = (lineEnd.x - lineStart.x) / lineStep; ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'; ctx.fillRect(0, 0, canvas.width, canvas.height); const poleLineWidth = 10; ctx.lineWidth = poleLineWidth; // left line const leftP1x = canvas.width / 4; const leftP1y = canvas.height; const leftP2x = leftCircleCenterX; const leftP2y = leftCircleCenterY; const leftVert = calcVertical(leftP1x, leftP1y, leftP2x, leftP2y, poleLineWidth); const linGradLeft = ctx.createLinearGradient(leftVert.pv1x, leftVert.pv1y, leftVert.pv2x, leftVert.pv2y); linGradLeft.addColorStop(0, 'rgb(64, 64, 64)'); linGradLeft.addColorStop(0.5, 'rgb(192, 192, 192)'); linGradLeft.addColorStop(1, 'rgb(64, 64, 64)'); ctx.strokeStyle = linGradLeft; ctx.beginPath(); ctx.moveTo(leftP1.........完整代码请登录后点击上方下载按钮下载查看
网友评论0