JS
var c = document.getElementById('stars'),
ctx = c.getContext("2d"),
t = 0; // time
c.width = 300;
c.height = 300;
var w = c.width,
h = c.height,
z = c.height,
v = Math.PI; // angle of vision
(function animate() {
Math.seedrandom('bg');
ctx.globalAlpha = 1;
for (var i = 0; i <= 100; i++) {
var x = Math.floor(Math.random() * w), // pos x
y = Math.floor(Math.random() * h), // pos y
r = Math.random()*2 + 1, // radius
a = Math.random()*0.5 + 0.5, // alpha
// linear
d = (r*a), // depth
p = t*d; // pixels per t
x = x - p; // movement
x = x - w * Math.floor(x / w); // go around when x < 0
(function draw(x,y) {
var gradient = ctx.createRadialGradient(x, y, 0, x + r, y + r, r * 2);
gradient.addColorStop(0, 'rgba(255, 255, 255, ' + a + ')');
gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
ctx.beginPath();
ctx.arc(x, y, r, 0, 2*Math.PI);
ctx.fillStyle = gradient;
ctx.fill();
return draw;
})(x, y);
}
ctx.restore();
t += 1;
requestAnimationFrame(function() {
ctx.clearRect(0, 0, c.width, c.height);
animate();
});
})();
HTML
<canvas id="stars"></canvas>
CSS
canvas {
background: black;
}
目前它所做的是使用考虑星星的不透明度和大小的 delta X 来动画每个星星,因此最小的星星看起来移动较慢。
使用 p = t;
使所有星星以相同的速度移动。
问题
我正在寻找一个明确定义的模型,其中速度给人们一种星星围绕观察者旋转的错觉,定义为旋转中心 cX,cY
和视角 v
的角度,这是可以看到的 2π 的什么部分(如果圆的中心不是屏幕中心,则半径应至少为最大部分)。我正在努力找到一种方法,即使对于旋转 π 的中心圆也将该余弦应用于星运动的速度。
这些图解可能会进一步解释我的要求:
居中圆:
非中心:
不同视角:
我真的不知道该如何前进。我已经有些慌了。您能否帮助我迈出一些第一步吗?
谢谢。
更新
我已经在这段代码中取得了一些进展:
// linear
d = (r*a)*z, // depth
v = (2*Math.PI)/w,
p = Math.floor( d * Math.cos( t * v ) ); // pixels per t
x = x + p; // movement
x = x - w * Math.floor(x / w); // go around when x < 0
这里,p
是一个粒子在均匀圆周运动中的x坐标,v
是角速度。但这会产生钟摆效应。我不确定如何更改这些方程以创造观察者转动的幻象。
更新 2:
快成功了。Freenode频道##Math的一位用户很友好地建议使用以下计算方法:
// linear
d = (r*a), // depth
p = t*d; // pixels per t
x = x - p; // movement
x = x - w * Math.floor(x / w); // go around when x < 0
x = (x / w) - 0.5;
y = (y / h) - 0.5;
y /= Math.cos(x);
x = (x + 0.5) * w;
y = (y + 0.5) * h;
这个实现效果上看起来不错,但是在变量方面没有一个明确定义的模型(它只是“hack”了这个效果),因此我无法看到实现不同实现的简单方法(更改中心,视角)。真正的模型可能与这个非常相似。
更新3
根据Iftah的回复,我能够使用Sylvester将旋转矩阵应用于需要先保存在数组中的星星。现在每颗星星的z
坐标已确定,半径r
和不透明度a
也是由它派生出来的。代码有很大的不同和长度,所以我没有发布它,但这可能是朝着正确方向迈出的一步。我还无法使其持续旋转。在每帧上使用矩阵操作似乎在性能方面代价高昂。
p = f(d)
,它使用余弦函数来模拟在截面v
的圆中 x 的变化。正如你所指出的那样,有一个 cZ 变量在第一个示例中我没有放置,我会添加它。 - Alain Jacomet Forte