Система частиц на HTML5 Canvas
1 2 |
<canvas id="testCanvas"></canvas> <script src="/js/proton-1.0.0.min.js"></script> |
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 |
<script> var canvas; var context; var proton; var renderer; var emitter; var mouseObj; var bgImg; var repulsionBehaviour, crossZoneBehaviour; Main(); function Main() { canvas = document.getElementById("testCanvas"); canvas.width = 1003; canvas.height = 610; context = canvas.getContext('2d'); loadImage(); } function beginScene() { createProton(); createRenderer(); tick(); canvas.addEventListener('mousemove', mousemoveHandler, false); } function loadImage() { var image = new Image() image.onload = function(e) { bgImg = e.target; beginScene(); } image.src = '/img/bg1.jpg'; }; function createProton() { proton = new Proton; emitter = new Proton.Emitter(); emitter.damping = 0.0075; emitter.rate = new Proton.Rate(50); // Количество частиц emitter.addInitialize(new Proton.ImageTarget('/img/particle.png', 32)); emitter.addInitialize(new Proton.Position(new Proton.RectZone(0, 0, 1003, 550))); emitter.addInitialize(new Proton.Mass(1), new Proton.Radius(Proton.getSpan(5, 10))); mouseObj = {}; repulsionBehaviour = new Proton.Repulsion(mouseObj, 0, 0); crossZoneBehaviour = new Proton.CrossZone(new Proton.RectZone(-2, 0, 1005, 550), 'cross'); emitter.addBehaviour(repulsionBehaviour, crossZoneBehaviour); emitter.addBehaviour(new Proton.Scale(Proton.getSpan(.1, .6))); emitter.addBehaviour(new Proton.Alpha(.5)); emitter.addBehaviour(new Proton.RandomDrift(10, 10, .2)); emitter.addBehaviour({ initialize: function(particle) { particle.tha = Math.random() * Math.PI; particle.thaSpeed = 0.015 * Math.random() + 0.005; }, applyBehaviour: function(particle) { particle.tha += particle.thaSpeed; particle.alpha = Math.abs(Math.cos(particle.tha)); } }); emitter.emit('once'); proton.addEmitter(emitter); } function mousemoveHandler(e) { if (e.layerX || e.layerX == 0) { mouseObj.x = e.layerX; mouseObj.y = e.layerY; } else if (e.offsetX || e.offsetX == 0) { mouseObj.x = e.offsetX; mouseObj.y = e.offsetY; } repulsionBehaviour.reset(mouseObj, 5, 100); } function createRenderer() { renderer = new Proton.Renderer('canvas', proton, canvas); renderer.onProtonUpdate = function() { if (bgImg) context.drawImage(bgImg, 0, 0); }; renderer.start(); } function tick() { requestAnimationFrame(tick); proton.update(); } </script> |