访问 javascript 对象中的第 i 个数组

Accessing ith array within a javascript object

我正在阅读一本包含以下代码的书,我似乎无法显示圆圈之间的线条。好像是因为如果我这样做

drawLine(context, 1, 1, 100, 100, 3);

它有效,但是如果我这样做:

drawLine(context, untangleGame.circles[1].x, 1, 100, 100, 3);

它不会工作。所以我的问题是如何访问该值。这是一本书中的示例,其中使用了 jQuery。

就是这段代码,从第一个圆圈到每个其他圆圈画一条线,然后遍历其他圆圈:

for (var i = 0; i < untangleGame.circles.length; i++) {
    var startPoint = untangleGame.circles[i];
    for (var j = 0; j < i; j++) {
        var endPoint = untangleGame.circles[j];
        drawLine(context, startPoint.x, startPoint.y, endPoint.x, endPoint.y, 1);
        untangleGame.lines.push(new Line(startPoint, endpoint,
        untangleGame.thinLineThickness));
    }
}

我这里有例子:

http://jsfiddle.net/5wdjpryo/

我想玩的游戏叫 untangle。

您需要初始化 untangleGame 对象,请参阅此更新 http://jsfiddle.net/5wdjpryo/1/ 基本上画圈的时候加上var c = new Circle(x, y); untangleGame.circles.push(c);

    var canvas = document.getElementById('game');

    // canvas height and width:
    var width = canvas.width;
    var height = canvas.height;

    function Circle(x, y, radius) {
        this.x = x;
        this.y = y;
    }



    var context = canvas.getContext && canvas.getContext('2d');

    function drawCircle(context, x, y, radius) {
        context.fillStyle = 'green';
        context.beginPath();
        context.arc(x, y, radius, 0, Math.PI * 2, true);
        context.closePath();
        context.fill();
    }

    drawCircle(context, 100, 100, 10);

    // draw random 5 circles:
    var circleRadius = 10;
    var circlesCount = 5;

        // the game object:
    var untangleGame = {
        circles: [],
        thinLineThickness: 1,
        lines: []
    };

    for (var i = 0; i < circlesCount; i++) {
        var x = Math.random() * width;
        var y = Math.random() * height;
        var c = new Circle(x, y);
        untangleGame.circles.push(c);
        drawCircle(context, x, y, 10);
    }

    // drawing line and line object:
    function Line(startPoint, endpoint, thickness) {
        this.startPoint = startPoint;
        this.endPoint = endPoint;
        this.thickness = thickness;
    }




    function drawLine(context, x1, y1, x2, y2, thickness) {
        context.beginPath();
        context.moveTo(x1, y1);
        context.lineTo(x2, y2);
        context.lineWidth = thickness;
        context.strokeStyle = "#cfc";
        context.stroke();
    }

    // checking that drawLine works
    drawLine(context, 1, 1, 100, 100, 3);

    for (var i = 0; i < untangleGame.circles.length; i++) {
        var startPoint = untangleGame.circles[i];
        for (var j = 0; j < i; j++) {
            var endPoint = untangleGame.circles[j];
            drawLine(context, startPoint.x, startPoint.y, endPoint.x, endPoint.y, 1);
            untangleGame.lines.push(new Line(startPoint, endPoint,
            untangleGame.thinLineThickness));
        }
    }