canvas 3D旋转球
canvas 3D旋转球
by pleasureswx123
HTML
<canvas id='canvas' width=500 height=600 style='background-color:rgb(0,0,0)'>
This browser does not support html5.
</canvas>
CSS
body {
background:#000;
}
JavaScript
(function () {
function Garden(canvas) {
this.canvas = canvas;
this.ctx = this.canvas.getContext('2d');
// 三维系在二维上的原点
this.vpx = undefined;
this.vpy = undefined;
this.balls = [];
this.angleY = 0;
this.angleX = 0;
}
Garden.prototype = {
setBasePoint: function (x, y) {
this.vpx = x;
this.vpy = y;
},
createBall: function (x, y, z, ballR) {
this.balls.push(new Ball(this, x, y, z, ballR));
},
render: function () {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.balls.sort(function (a, b) {
return b.z - a.z
});
for (var i = 0; i
< this.balls.length; i++) {
this.balls[i].rotateY();
this.balls[i].rotateX();
this.balls[i].draw(i);
}
},
setListener: function () {
var that = this;
document.addEventListener('mousemove', function (event) {
var x = event.clientX - that.vpx;
var y = event.clientY - that.vpy;
that.angleY = -x * 0.0001;
that.angleX = y * 0.0001;
});
}
};
function Ball(garden, x, y, z, ballR) {
this.garden = garden;
// 三维上坐标
this.x = x === undefined ? Math.random() * 200 - 100 : x;
this.y = y === undefined ? Math.random() * 200 - 100 : y;
this.z = z === undefined ? Math.random() * 200 - 100 : z;
this.r = Math.floor(Math.random() * 255);
this.g = Math.floor(Math.random() * 255);
this.b = Math.floor(Math.random() * 255);
// 三维上半径
this.ballR = ballR === undefined ? 10 + Math.random() * 10 : ballR;
// 二维上半径
this.radius = undefined;
// 二维上坐标
this.x2 = undefined;
this.y2 = undefined;
}
...