Canvas学習(3) 3D
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.centerX = this.width * 0.5;
this.centerY = this.height * 0.5;
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();
return obj;
},
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 Point = Class();
Point.prototype = {
initialize: function(radius, color) {
this.x = 0;
this.y = 0;
this.px = 0;
this.py = 0;
this.pz = 0;
...