简体   繁体   English

JS将lineTo随机化

[英]JS randomize lineTo

I need to randomize the coordinates of shapes. 我需要随机化形状的坐标。 I know I need to somehow introduce the Math.floor(Math.Random * num); 我知道我需要以某种方式介绍Math.floor(Math.Random * num); line in there, but nothing I do seems to work. 线在那里,但我似乎无济于事。

This is the block with the filled in coordinates I am trying to randomize. 这是我尝试随机填充的座标。

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.lineWidth="5";
ctx.strokeStyle="black";  
ctx.moveTo;
ctx.lineTo(100,20);
ctx.lineTo(30,400);
ctx.lineTo(300,40);
ctx.lineTo(10,20);
ctx.stroke();

I've searched and searched and found nothing directly on this for some reason. 由于某种原因,我一直在搜索中搜索并没有直接找到任何内容。 Sorry this is such a basic question too, I'm really new to this and still learning the basics. 抱歉,这也是一个基本问题,我真的很陌生,仍然在学习基本知识。

Thank you in advance 先感谢您

Here is a fiddle showing the things I explain below. 这是一个小提琴,显示了我在下面解释的内容。

Check this page for syntax regarding the Canvas. 检查此页面以获取有关Canvas的语法。

If you want to be able to quickly and easily designate random coordinates, you can wrap it up in a function. 如果您希望能够快速轻松地指定随机坐标,可以将其包装在函数中。

function randCoord(factor){
    return Math.random() * factor;
}

and then use it like this: 然后像这样使用它:

// all of these will go to different points
ctx.moveTo(randCoord(300),randCoord(100));
ctx.lineTo(randCoord(300),randCoord(100));
ctx.lineTo(randCoord(300),randCoord(100));
ctx.lineTo(randCoord(300),randCoord(100));

You could set a default scale: 您可以设置默认比例:

function randCoord(factor){
    if (factor == undefined){
        factor = 100;
    }
    return Math.random() * factor;
}

Which would allow you to simply write the function name. 这将使您可以简单地编写函数名称。

ctx.lineTo(randCoord(),randCoord());

You can also make another function that just adds a random additional point 您还可以创建另一个仅添加随机附加点的功能

function addRandomPoint(xFactor, yFactor) {
    ctx.lineTo( randCoord(xFactor), randCoord(yFactor) );
}

// these will all add new points
addRandomPoint();
addRandomPoint();
addRandomPoint(200, 300);
addRandomPoint(-100, 25);

And then wrap it up in loop to make many points 然后将其循环包装以得出很多要点

// this will add 10 new points
for (var i = 0; i < 10; i++) {
    addRandomPoint();
}

So you could do this: 因此,您可以这样做:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.lineWidth="5";
ctx.strokeStyle="black";
    ctx.moveTo(10, 10);
for (var i = 0; i < 10; i++) {
    addRandomPoint();
}
ctx.stroke();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM