首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >生成随机图坐标

生成随机图坐标
EN

Stack Overflow用户
提问于 2013-06-26 19:41:56
回答 1查看 1.4K关注 0票数 0

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

代码语言:javascript
复制
<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

如果有人能清楚地解释这一点,我将对其进行编辑。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-06-26 22:54:02

就像鲍尔普罗建议的那样,你只需将Point3的x&y设置为前一个。我做了一个数组,并做了一些循环,让它工作得更好一些。查看代码here

代码语言:javascript
复制
<!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>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17319059

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档