Звёздное небо с Parallax эффектом на HTML5 и jQuery
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
.background { position: fixed; top: 0; right: 0; bottom: 0; left: 0; background: #111; z-index: -1; } .canvas { position: absolute; z-index: -1; } .back { top: -100px; left: -100px; } .mid { top: -200px; left: -200px; } .front { top: -400px; left: -400px; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
<div class="background"> <div class="canvas back"> <canvas id="canvas-back"></canvas> </div> <div class="canvas mid"> <canvas id="canvas-mid"></canvas> </div> <div class="canvas front"> <canvas id="canvas-front"></canvas> </div> </div> <script> $(document).ready(function() { var $background = $('div.background'), backgroundWidth = $background.width(), backgroundHeight = $background.height(), canvasBack = document.getElementById('canvas-back'), canvasMid = document.getElementById('canvas-mid'), canvasFront = document.getElementById('canvas-front'); canvasBack.width = backgroundWidth + 100; canvasMid.width = backgroundWidth + 200; canvasFront.width = backgroundWidth + 400; canvasBack.height = backgroundHeight + 100; canvasMid.height = backgroundHeight + 200; canvasFront.height = backgroundHeight + 400; createBackground(canvasBack, 5000, 100, 0.7); createBackground(canvasMid, 4000, 100, 1.5); createBackground(canvasFront, 2000, 100, 2); function createBackground(canvas, arcCount, alpha, maxArcSize) { var context = canvas.getContext('2d'), sarcX, arcY, arcR, arcS, arcE, r, g, b, a, color; for (var i = 0; i < arcCount; i++) { r = Math.floor(Math.random() * 255); g = Math.floor(Math.random() * 255); b = Math.floor(Math.random() * 255); a = Math.round(Math.random() * alpha) / 100; color = 'rgba(' + r + ', ' + g + ', ' + b + ', ' + a + ')'; context.fillStyle = color; arcX = Math.floor(Math.random() * canvas.width); arcY = Math.floor(Math.random() * canvas.height); arcR = Math.random() * maxArcSize; arcS = Math.ceil(Math.random() * 360); arcE = Math.random() * 2; context.beginPath(); context.arc(arcX, arcY, arcR, arcS, arcE * Math.PI); context.fill(); } } document.addEventListener('mousemove', handleBackground); function handleBackground(e) { var mouseX = -(Math.round((e.clientX / backgroundWidth) * 100)), mouseY = -(Math.round((e.clientY / backgroundHeight) * 100)); positionBackground($('div.canvas.back'), 1, mouseX, mouseY); positionBackground($('div.canvas.mid'), 2, mouseX, mouseY); positionBackground($('div.canvas.front'), 4, mouseX, mouseY); } function positionBackground(div, offset, mouseX, mouseY) { var offsetX = String(mouseX * offset) + 'px', offsetY = String(mouseY * offset) + 'px'; div.css({ left: offsetX, top: offsetY }); } }); </script> |