複数のパーティクル(粒子)が動く様子を表現してみます。
デモ画面では、半径r=5の円のパーティクルを30個Canvas中央(300,250)にて生成しています。各パーティクルの進行方向(速度)はランダムに設定しています。
パーティクルの描写や動き方などのメソッドは、prototypeを利用して記述していきます。prototypeの役割については以下の関連ページをご覧下さい。
関連ページ
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 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>パーティクル</title> <style> *{ margin: 0px; padding: 0px; } #canvas { background-color: #000; } </style> <head> <body> <canvas id="canvas" width="600" height="500"> ブラウザが対応しておりません。 </canvas> <script> window.addEventListener('load', draw, false); function draw(){ var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var R = 5; //パーティクルの半径 var NUM = 30; //パーティクルの数 var particles = []; //パーティクルを管理する配列 var Particle = function(ctx, x, y, speedx, speedy){ //パーティクルのコンストラクタ this.ctx = ctx; this.x = x; this.y = y; this.speedx = speedx; this.speedy = speedy; } Particle.prototype.draw = function(){ //パーティクルの描写 ctx = this.ctx; ctx.beginPath(); ctx.fillStyle = 'green'; ctx.arc(this.x, this.y, R, 0, Math.PI*2.0, true); ctx.fill(); } Particle.prototype.updatePosition = function(){ //パーティクルの移動 this.x +=this.speedx; this.y +=this.speedy; if(this.x < R || this.x > 600-R){ this.speedx *= -1; } if(this.y < R || this.y > 500-R){ this.speedy *= -1; } } Particle.prototype.render = function(){ this.draw(); this.updatePosition(); } for (var i = 0; i < NUM; i++) { //パーティクルインスタンスを30個生成し配列に格納 positionX = 300; positionY = 250; speedx = Math.random()*10-5; //-5から5の間をランダムに生成 speedy = Math.random()*10-5; particle = new Particle(ctx, positionX, positionY, speedx, speedy); //インスタンスを生成 particles.push(particle); //生成したパーティクルを配列に格納 } function loop() { ctx.clearRect(0 ,0, canvas.width, canvas.height); //キャンバス上の図形をクリアにする particles.forEach(function (e) { //格納されたparticles配列の各要素を実行 e.render(); }); requestAnimationFrame(loop); } loop(); } </script> </body> </html> |
流れとしては、まずParticleコンストラクタ関数を作成。パーティクルの描写や移動等のメソッドは、prototypeプロパティを利用して宣言しています。
66〜73行目では、30個生成するインスタンスに対して、具体的な生成位置座標(固定)と速度(ランダム)を指定し、配列に格納しています。
参照文献