這裏是一個fiddle顯示我在下面解釋的事情。
查看this page瞭解關於畫布的語法。
如果您希望能夠快速方便地指定隨機座標,可以將其包含在函數中。
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();
你有什麼試過嗎?它是如何工作的(錯誤的,不需要的行爲等)? – Dan