随机数圈

时间:2016-02-13 15:34:41

标签: javascript canvas random

我得到这个代码在画布上绘制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);
}

1 个答案:

答案 0 :(得分: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);
}