html5 canvas获取坐标系,HTML5 Canvas球坐标系投影到二维直角坐标系实例演示

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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值