2014-01-09 71 views
2

我需要隨機化形狀的座標。 我知道我需要以某種方式介紹Math.floor(Math.Random * num);在那裏,但我沒有做似乎工作。JS randomize lineTo

這是我想隨機填充座標的塊。

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

我搜索和搜索,由於某種原因沒有發現任何東西直接。 對不起,這也是一個基本問題,我真的很陌生,仍然在學習基礎知識。

預先感謝您

+1

你有什麼試過嗎?它是如何工作的(錯誤的,不需要的行爲等)? – Dan

回答

1

這裏是一個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(); 
+0

非常感謝。我打算把這個集成起來,我會告訴你它是否工作正常。 我會綠色的答案,但我還沒有賺取我的條紋。 再次歡呼。 – user3178364

+0

它完美的作品。再次感謝你! – user3178364

+0

不客氣! @ user3178364你能接受答案嗎?您可能無法註冊它,但您應該能夠選中對號。 – BenjaminGolder