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

Canvas模拟行星轨道失败:cos/sin函数相关问题求助

行星环绕轨道修复及文字颜色适配方案

一、行星环绕轨道问题修复(针对JS 138-155行三角函数错误)

JS中Math.cos()和Math.sin()仅支持弧度值作为参数,若你的代码直接传入0-360的角度值,会导致位置计算完全错误,无法形成环绕轨道。

核心修复步骤:

  1. 将角度转换为弧度,公式:弧度 = 角度 * Math.PI / 180
  2. 确保每帧更新时角度按固定值递增,维持持续环绕动画

错误代码示例(推测你的138-155行逻辑):

// 错误:直接使用角度计算位置
function updatePlanetPosition(planet) {
  planet.x = centerX + Math.cos(planet.angle) * planet.orbitRadius;
  planet.y = centerY + Math.sin(planet.angle) * planet.orbitRadius;
  planet.angle += 1; // 角度递增
}

修复后代码:

// 正确:先转弧度再计算位置
function updatePlanetPosition(planet) {
  const radian = planet.angle * Math.PI / 180; // 角度转弧度
  planet.x = centerX + Math.cos(radian) * planet.orbitRadius;
  planet.y = centerY + Math.sin(radian) * planet.orbitRadius;
  planet.angle += 0.5; // 可调整递增速度控制环绕快慢
}

二、无图片时文字自动变红的实现

通过监听图片的error事件,在加载失败时修改对应文字的颜色:

静态DOM结构场景:

<div class="planet-item">
  <img src="planet.png" class="planet-img" alt="行星">
  <span class="planet-text">火星</span>
</div>
// 批量处理所有行星图片
document.querySelectorAll('.planet-img').forEach(img => {
  img.addEventListener('error', function() {
    // 找到相邻的文字元素并修改颜色
    const textEl = this.nextElementSibling;
    if (textEl) textEl.style.color = 'red';
  });
});

动态创建元素场景:

function createPlanet(planetName, imgUrl) {
  const img = new Image();
  const textEl = document.createElement('span');
  
  textEl.textContent = planetName;
  textEl.style.color = 'white'; // 默认白色

  // 绑定加载失败事件
  img.addEventListener('error', () => {
    textEl.style.color = 'red';
  });

  img.src = imgUrl;
  // 将元素添加到页面容器
  document.getElementById('solar-system').append(img, textEl);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:27:31