2016-02-13 94 views
-1

我得到了這個代碼在畫布上繪製10個正常和10個濺出的圓,但我需要畫出1到20之間的隨機數。我該怎麼做?隨機數的圓圈

var randomColour; 
var randomSize; 
var randomNumber; 
var xPos; 
var yPos; 
var i; 
var j; 

c = document.getElementById("myCanvas"); 
ctx = c.getContext("2d"); 

function drawFilledCircle(size,xPos,yPos,colour){ 
    ctx.beginPath(); 
    ctx.arc(xPos,yPos,size,0,2*Math.PI); 
    ctx.fillStyle = colour; 
    ctx.fill(); 
} 

function drawSplatter(size,xPos,yPos,colour){ 
    for(j=0;j<10;j++){ 
    var splatSize = size/Math.round(Math.random()*30); 
    drawFilledCircle(splatSize,xPos + Math.round(Math.random()*40),yPos + Math.round(Math.random()*50),colour); 
    } 
} 

for(i=0;i<10;i++){ 
    randomColour = '#' + Math.random().toString(16).substring(2, 8); 
    randomSize = Math.round(Math.random()*50); 
    xPos = Math.round(Math.random()*640); 
    yPos = Math.round(Math.random()*480); 
    drawFilledCircle(randomSize, xPos, yPos, randomColour); 
    drawSplatter(randomSize, xPos, yPos, randomColour); 
} 

回答

2

試試這個

//Find random number between 1 and 20. 
var rand = Math.floor(Math.random() * 20) + 1; 

for(i = 0; i < rand; i++){ 
    randomColour = '#' + Math.random().toString(16).substring(2, 8); 
    randomSize = Math.round(Math.random()*50); 
    xPos = Math.round(Math.random()*640); 
    yPos = Math.round(Math.random()*480); 
    drawFilledCircle(randomSize, xPos, yPos, randomColour); 
    drawSplatter(randomSize, xPos, yPos, randomColour); 
}