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

如何初始化对象内的函数?rays对象太阳光线效果初始化故障求助

修复太阳光线效果代码的问题

我瞅了瞅你这段实现太阳光线的代码,发现几个关键问题导致你折腾了好几个小时都出不来效果,给你把问题捋清楚并修复好了:

问题解析

  • 全局变量污染:代码里的c、length、midx、midy、angle、i这些变量都没声明,会自动变成全局变量,很容易和其他代码冲突,导致函数执行异常。
  • Canvas尺寸缺失:如果你的canvas只靠CSS设置宽高,会让绘制的图形拉伸变形,必须保证canvas的width和height属性与实际显示尺寸匹配。
  • 路径叠加问题:原代码里没有在每次绘制光线前重新开启路径,会导致所有光线路径叠加,影响最终渲染效果。
  • 动画帧率偏低:原代码用100ms的间隔执行动画,会显得卡顿,改成16ms更接近60fps,动画更流畅。

修复后的完整代码

var rays = new Object({ 
  canvas: false, 
  context: false, 
  interval: false, 
  offset: 0, 
  init: function(id, colour1, colour2){ 
    this.canvas = document.getElementById(id); 
    this.context = this.canvas.getContext('2d'); 
    // 设置canvas实际尺寸(可根据需求调整为固定值)
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    this.canvas.style.background = colour1; 
    this.context.fillStyle = colour2; 
    clearInterval(this.interval); 
    // 用箭头函数保证this始终指向rays对象
    this.interval = setInterval(() => { 
      this.offset += 0.005; 
      this.draw(); 
    }, 16); 
    this.draw(); 
  }, 
  getXY: function(x, y, d, a){ 
    return { 
      x: x + d * Math.cos(a), 
      y: y + d * Math.sin(a) 
    }; 
  }, 
  draw: function(){ 
    const c = this.canvas; 
    this.context.clearRect(0, 0, c.width, c.height); 
    const length = Math.max(c.width, c.height); 
    const midx = c.width / 2, midy = c.height / 2; 
    const d = 12; 
    for(let i = 0;i < d;i++){ 
      const angle = (Math.PI * 2 / d) * i + this.offset; 
      this.context.beginPath(); // 每次绘制光线前开启新路径
      this.context.moveTo(midx, midy); 
      const c1 = this.getXY(midx, midy, length, angle + d / 100); 
      this.context.lineTo(c1.x, c1.y); 
      const c2 = this.getXY(midx, midy, length, angle - d / 100); 
      this.context.lineTo(c2.x, c2.y); 
      this.context.lineTo(midx, midy); 
      this.context.fill(); 
    }; 
    this.context.beginPath(); 
    this.context.arc(midx, midy, c.width * c.height / 20000, 0, Math.PI * 2, true); 
    this.context.closePath(); 
    this.context.fill(); 
  } 
});

正确使用步骤

  1. 在HTML里添加canvas元素:
<canvas id="sunRays"></canvas>
  1. 调用初始化函数(建议放在页面加载完成事件里):
window.onload = function() {
  // 参数分别是canvas的id、背景色、光线颜色
  rays.init('sunRays', '#000000', '#ffd700');
};

如果需要固定尺寸的canvas,把init里的window.innerWidth和window.innerHeight改成你需要的数值就行,比如800和600。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:00:38