生成随机图形坐标

时间:2013-06-26 11:41:56

标签: javascript graph

以下代码将在图形(画布)上生成两个随机点,这些点可以与一条线连接。

<script>
function random() {
var point1X = (Math.floor(Math.random() * 10) + 1);
var point1Y = (Math.floor(Math.random() * 2) - 10); // first two lines generate first coordinate on graph
var point2X = (Math.floor(Math.random() * 100) + 10);
var point2Y = (Math.floor(Math.random() * 2) - 10); // second two lines generate second point

document.getElementById("empty").innerHTML += "(" + point1X + ", " + point1Y + ") (" +      point2X + ", " + point2Y + ")<br />"; // here coordinates are displayed on the page.
}
</script>

我希望生成的第二个坐标等于第三个坐标,因为所有内容都应该使用直线连接(但生成的第四个坐标应该不同)。

我发现这很难解释,所以希望这个图应该有所帮助:http://i6.minus.com/jKIhdChUNWZt7.png

如果有人能够清楚地解释清楚,我会对此进行编辑。

1 个答案:

答案 0 :(得分:1)

像Paulpro建议的那样,你只需设置point3的x&amp;你到上一个。我做了一个数组并做了一些循环,让它工作得更好一点。查看代码here

<!DOCTYPE html>
<html>
<head>
<script>
    var xArray = [];
    var yArray = [];

    xArray.push((Math.floor(Math.random() * 10) + 1));
    xArray.push((Math.floor(Math.random() * 10) + 1));
    yArray.push((Math.floor(Math.random() * 2) - 10));
    yArray.push((Math.floor(Math.random() * 2) - 10));

    function myFunction()
    {
        xArray[xArray.length] = xArray[xArray.length - 1];
        yArray[yArray.length] = yArray[yArray.length - 1];

        var pointX = (Math.floor(Math.random() * 100) + 10);
        var pointY = (Math.floor(Math.random() * 2) - 10);

        xArray.push(pointX);
        yArray.push(pointY);

        for(var i = 0; i < xArray.length; i++)
        {
            document.getElementById("empty").innerHTML += "(" + xArray[i] + ", " + yArray[i] + ")</br>";
        }
        document.getElementById("empty").innerHTML += "</br>";
     }
 </script>
</head>
<body>

<button onclick="myFunction()">Click me</button>

<p id="empty"></p>

</body>
</html>
相关问题