You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于地球自转计算当前太阳角度?WebGL地球光照实现

计算基于当前时间的dayTime值(0-24小时映射到0-1)

完全不需要调用任何API,直接用JavaScript的Date对象就能算出dayTime值:

  • 从new Date()里提取当前的小时、分钟、秒数
  • 将分钟和秒数转换成小时的小数部分,相加得到总小时数
  • 把总小时数除以24,就得到0到1之间的dayTime值

具体代码实现如下:

// 计算当前时间对应的dayTime(0-1)
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const totalHours = hours + minutes / 60 + seconds / 3600;
const dayTime = totalHours / 24; // 范围0-1

// 修正角度计算:dayTime是0-1对应0-360度,所以应该是360 * dayTime
const d = degToRad(360 * dayTime);
const sunPos = new Vec3(
    Math.cos(d),
    Math.sin(d) * Math.sin(0), // 这里的0如果是太阳倾角,可以根据需求调整
    Math.sin(d) * Math.cos(0)
);

this.program.uniforms.sunPosition.value = sunPos

注意:你原来代码里的360 / dayTime是错误的,当dayTime接近0时会导致角度趋近于无穷大,正确的应该是用360 * dayTime,这样dayTime=0对应0度,dayTime=1对应360度(和0度重合),符合一天的循环逻辑。

内容的提问来源于stack exchange,提问作者flks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 03:10:34