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

调用drawGrid函数绘制向量网格时页面崩溃,求排查原因

问题原因与修复方案

核心问题

drawGrid函数里的grid.push(new Array())是导致页面崩溃的直接原因。在遍历grid数组的过程中,每次循环都往grid里添加新的空数组,使得grid.length持续增大,外层for循环永远无法终止,引发无限循环,最终导致页面无响应崩溃。

修复后的关键代码

删除drawGrid中多余的grid.push(new Array())语句即可,修复后的drawGrid函数如下:

function drawGrid() {
    let vector
    for(let i = 0; i < grid.length; i++) {
        for(let j = 0; j < grid[i].length; j++) {
            vector = grid[i][j]
            vector.draw()
            console.log(vector)
        }
    }
}

完整修复代码

const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')
canvas.width = innerWidth
canvas.height = innerHeight

class Vector {
    constructor(x, y, magnitude, angle) {
        this.x = x
        this.y = y
        this.mag = magnitude
        this.ang = angle
        this.tx = magnitude * Math.cos(angle) + x
        this.ty = magnitude * Math.sin(angle) + y
    }

    draw() {
        c.beginPath()
        c.moveTo(this.x, this.y)
        c.lineTo(this.tx, this.ty)
        c.stroke()
    }
}

const resolution = 20;

let grid = []

function init() {
    // 创建向量网格
    for(let i = 0; i < canvas.height; i += resolution) {
        grid.push(new Array())
        for(let j = 0; j < canvas.width; j += resolution) {
            grid[i / resolution].push(new Vector(i, j, 7, Math.PI))
        }
    }

    drawGrid()
}

function drawGrid() {
    let vector
    for(let i = 0; i < grid.length; i++) {
        for(let j = 0; j < grid[i].length; j++) {
            vector = grid[i][j]
            vector.draw()
            console.log(vector)
        }
    }
}

// 启动程序
init()

额外优化建议

  • 可以给向量线条添加样式,比如c.strokeStyle = '#333'和c.lineWidth = 1,让可视化效果更清晰;
  • 调试完成后建议移除drawGrid中的console.log(vector),大量日志输出会影响页面性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 09:01:14