慕田峪4524236
你总是可以(从字面上)隐藏复杂性。Math.random.between = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);const createWeb = (el) => { const clock = { $canvas: el, logicalCenter: [Math.random.between(100, 400), Math.random.between(100, 400)], segments: 12, }; clock.segmentSize = (Math.PI * 2) / clock.segments; clock.$canvas.width = 500; clock.$canvas.height = 500; clock.ctx = clock.$canvas.getContext('2d'); clock.ctx.strokeStyle = 'orangered'; clock.ctx.lineWidth = 5; clock.ctx.fillStyle = 'white'; const draw = { arm: (atSegment) => { atSegment = atSegment % clock.segments; const degree = atSegment * clock.segmentSize; const handLength = clock.$canvas.width * 2; const [x, y] = [Math.cos(degree) * handLength, Math.sin(degree) * handLength]; clock.ctx.beginPath(); clock.ctx.moveTo(...clock.logicalCenter); clock.ctx.lineTo(x + clock.logicalCenter[0], y + clock.logicalCenter[1]); clock.ctx.stroke(); }, center: (radius) => { clock.ctx.beginPath(); clock.ctx.arc(...clock.logicalCenter, radius, 0, Math.PI * 2); clock.ctx.stroke(); }, border: (thickness) => { const [w, h] = [clock.$canvas.width, clock.$canvas.height]; clock.ctx.fillRect(0, 0, thickness, h); clock.ctx.fillRect(0, 0, w, thickness); clock.ctx.fillRect(0, h - thickness, w, thickness); clock.ctx.fillRect(w - thickness, 0, thickness, h); } }; draw.center(10); Array(clock.segments).fill(0) .map((_, i) => i) .forEach(draw.arm); draw.border(20);}document.querySelectorAll('.clock').forEach(createWeb);* { margin: 0; padding: 0;}.clock { position: relative; width: 200px; height: 200px; border: 3px orangered solid; box-sizing: border-box;}<canvas class="clock"></canvas><canvas class="clock"></canvas><canvas class="clock"></canvas>