gpt4 book ai didi

javascript - JS 随机化 lineTo

转载 作者:行者123 更新时间:2023-11-30 05:40:36 25 4
gpt4 key购买 nike

我需要随机化形状的坐标。我知道我需要以某种方式介绍 Math.floor(Math.Random * num);在那里排队,但我所做的一切似乎都不起作用。

这是我要随机化的填充了坐标的 block 。

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();

出于某种原因,我已经搜索和搜索并没有直接找到任何东西。抱歉,这也是一个基本问题,我对此很陌生,仍在学习基础知识。

提前致谢

最佳答案

这是一个fiddle显示我在下面解释的内容。

检查 this page有关 Canvas 的语法。

如果您希望能够快速轻松地指定随机坐标,您可以将其包装在一个函数中。

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

然后像这样使用它:

// 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));

您可以设置默认比例:

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

这将允许您简单地编写函数名称。

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

你也可以创建另一个函数,只添加一个随机的附加点

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

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

然后将其包裹在循环中以形成许多点

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

所以你可以这样做:

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();

关于javascript - JS 随机化 lineTo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21025677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com