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

时间:2015-01-30 19:58:09

标签: javascript canvas

我跟着一本带有以下代码的书,我似乎无法让圆圈之间的线条显示出来。这似乎是因为我做了

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/

我试图关注的游戏称为解开。

1 个答案:

答案 0 :(得分:0)

您需要初始化您的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));
        }
    }