这是一个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();