Дождь внутри любого блока на HTML5 Canvas
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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
<canvas id="c"></canvas> <script> var rain = [], drops = []; var gravity = 0.2; var wind = 0.015; var rain_chance = 0.4; window.requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; var canvas = document.getElementById('c'); var ctx = canvas.getContext('2d'); canvas.width = 800; canvas.height = 360; //-------------------------------------------- var Vector = function(x, y) { this.x = x || 0; this.y = y || 0; }; Vector.prototype.add = function(v) { if (v.x != null && v.y != null) { this.x += v.x; this.y += v.y; } else { this.x += v; this.y += v; } return this; }; Vector.prototype.copy = function() { return new Vector(this.x, this.y); }; //-------------------------------------------- var Rain = function() { this.pos = new Vector(Math.random() * canvas.width, -50); this.prev = this.pos; this.vel = new Vector(); }; Rain.prototype.update = function() { this.prev = this.pos.copy(); this.vel.y += gravity; this.vel.x += wind; this.pos.add(this.vel); }; Rain.prototype.draw = function() { ctx.beginPath(); ctx.moveTo(this.pos.x, this.pos.y); ctx.lineTo(this.prev.x, this.prev.y); ctx.stroke(); }; //-------------------------------------------- var Drop = function(x, y) { var dist = Math.random() * 7; var angle = Math.PI + Math.random() * Math.PI; this.pos = new Vector(x, y); this.vel = new Vector(Math.cos(angle) * dist, Math.sin(angle) * dist); }; Drop.prototype.update = function() { this.vel.y += gravity; this.vel.x *= 0.95; this.vel.y *= 0.95; this.pos.add(this.vel); }; Drop.prototype.draw = function() { ctx.beginPath(); ctx.arc(this.pos.x, this.pos.y, 1, 0, Math.PI * 2); ctx.fill(); }; //-------------------------------------------- function update() { ctx.clearRect(0, 0, canvas.width, canvas.height); var i = rain.length; while (i--) { var raindrop = rain[i]; raindrop.update(); if (raindrop.pos.y >= canvas.height) { var n = Math.round(4 + Math.random() * 4); while (n--) drops.push(new Drop(raindrop.pos.x, canvas.height)); rain.splice(i, 1); } raindrop.draw(); } var i = drops.length; while (i--) { var drop = drops[i]; drop.update(); drop.draw(); if (drop.pos.y > canvas.height) drops.splice(i, 1); } if (Math.random() < rain_chance) rain.push(new Rain()); requestAnimFrame(update); } function init() { ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(60,135,235,1)'; ctx.fillStyle = 'rgba(60,135,235,1)'; update(); } init(); </script> |