user2166577
user2166577

Reputation:

Generating random graph coordinates

The below code will generate two random points on a graph (canvas) which could be connected with a line.

<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>

I want the second coordinates generated to be equivalent to the third coordinates made since everything should be connected using lines (however the fourth coordinates generated should be different).

I'm finding this very difficult to explain so hopefully this diagram should help: http://i6.minus.com/jKIhdChUNWZt7.png.

If anyone can explain this clearly, I'll edit this.

Upvotes: 0

Views: 1704

Answers (1)

Zach Saucier
Zach Saucier

Reputation: 25944

Like Paulpro suggested, you just set point3's x & y to the previous one's. I made an array and did some looping to let it work a little better. Check out the code 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>

Upvotes: 1

Related Questions