JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
function g(e) {
return document.getElementById(e);
}
var random = function() {
return (Math.random() * 10 >> 0) / 10;
}
var ctx = g('pad').getContext('2d');
ctx.scale(100, 100);
ctx.lineWidth = 0.002;
ctx.lineJoin = "round";
var Ball = function(x, y, r) {
this.theta = 0; //球坐标转角
this.eleva = 0; //球坐标仰角
this.radius = r || 1; //球坐标半径
this.pos = { //球坐标原点
x: x || 2,
y: y || 2
};
this.co = { //二维上的投影坐标
x: 0,
y: 0
};
this.col = { //颜色
r: 255,
g: 255,
b: 255,
a: 0.6
};
this.init = function() {
ctx.translate(this.pos.x, this.pos.y);
this.preview();
};
this.init();
};
/* 球坐标系转平面直角坐标系 */
Ball.prototype.iso = function(a, b, r) {
var x, y, z
x = r * Math.cos(a + this.theta) * Math.sin(b);
y = r * Math.sin(a + this.theta) * Math.sin(b);
z = r * Math.cos(b);
var fact = (y * Math.cos(this.eleva) + z * Math.sin(this.eleva) + 8) / 8;
y = y * Math.sin(this.eleva) + z * Math.cos(this.eleva);
x *= fact;
y *= fact;
return {
x: x,
y: y
};
}
Ball.prototype.preview = function() {
ctx.strokeStyle = 'rgba(' + this.col.r + ',' + this.col.g + ',' + this.col.b + ',' + this.col.a + ')';
ctx.clearRect(-2, -2, 4, 4);
ctx.beginPath();
this.sphere();
ctx.stroke();
}
Ball.prototype.sphere = function() {
var a, b;
for (a = 0; a < 2 * Math.PI; a += Math.PI / 12) {
for (b = 0; b < 2 * Math.PI; b += Math.PI / 12) {
if (b == 0 || b * 100 >> 0 == Math.PI * 100 >> 0 || b * 100 >> 0 == 2 * Math.PI * 100 >> 0) continue; /* 排除一些仰角(接近)为0/PI/2PI的点. */
this.co = this.iso(0, 0, 0);
ctx.moveTo(this.co.x, this.co.y);
this.co = this.iso(a, b, this.radius);
ctx.lineTo(this.co.x, this.co.y);
}
}
}
Ball.prototype.fluc = function() {
var that = this;
setInterval(function() {
that.theta += random() / 20;
that.eleva += random() / 20;
that.radius += (random() / 10 - 0.05);
if (that.radius < 0.5 || that.radius > 2) that.radius = 1;
that.preview();
}, 100)
};
new Ball(2, 2, 1).fluc();