Canvas学習(2) パーティクル

by seijitakagi

HTML

<div style="margin:0 auto; text-align:center;">
    <canvas id="canvas" width="480" height="480" style="margin:0 auto;"></canvas>
    <a href="javascript:void(0);" id="btn">start</a>
</div>

CSS

#btn {
    display: block;
    background: #ff0000;
    padding: 15px;
    margin: 10px auto;
    text-align: center;
    width: 8em;
    font-size: 12px;
    font-family: arial;
    color: #fff;
    text-decoration: none;
}

JavaScript

var Class = function(){return function(){this.initialize.apply(this,arguments)}}
var Stage = Class();
Stage.prototype = {
    initialize: function(canvasId, bgColor, rate) {
        this.rate = Math.round( 1000 / rate );
        this.canvas = document.getElementById( canvasId );
        this.context = this.canvas.getContext("2d");
        this.bgColor = bgColor;
        this.rect = this.canvas.getBoundingClientRect();
        this.mouseX = 0;
        this.mouseY = 0;
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        this.children = [];
        this.renderId = 0;
        this.render = null;
        this.rendering = false;
        var self = this;
        this.canvas.onmousemove = function(e) {
            self.mouseX = e.clientX - self.rect.left;
            self.mouseY = e.clientY - self.rect.top;
        };
    },
    refresh:function(){
        this.context.fillStyle = this.bgColor;
        this.context.fillRect(0, 0, this.canvas.width , this.canvas.height );
    },
    addChild:function(obj){
        this.refresh();
        this.children.push( obj );
        obj.stage = this;
        obj.draw();
    },
    update:function(){
        this.refresh();
        for( var i = 0; i < this.children.length; i++ ) {
            this.children[i].draw();
        }
    },
    renderStart:function(){
        if( this.render == null ) return;
        
        this.rendering = true;
        var self = this;
        this.renderId = setInterval( function(){
            self.render();
            self.update();
        }, this.rate );
    },
    renderStop:function(){
        this.rendering = false;
        clearInterval(this.renderId);   
    }
};

var Particle = Class();
Particle.prototype = {
    initialize: function(px, py, vx, vy, color) 
    {
        this.px = px;
        this.py = py;
        this.vx = vx;
        this.vy = vy;
        this.color = color;
        this.stage = null;
    },
    draw: function(){
        if( this.stage...