Home Ask Login Register

Developers Planet

Your answer is one click away!

Artis February 2016

Drawing Random Coloured Circles on html Canvas with js?

I'm just starting with js and need little help! I got these two functions, to draw circles and splattered circles, I need to create a for loop to draw 10 random coloured circles and 10 random splattered circles! how can i do it? thanks

<canvas id="myCanvas" width="550" height="400"></canvas>
<script>
    var randomColour;
    var randomSize;
    var xPos;
    var yPos;
    var i;
    var j;

    randomColour = '#' + Math.random().toString(16).substring(4); // random colour
    c = document.getElementById("myCanvas");
    ctx = c.getContext("2d");

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

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


</script>

Answers


wolfhammer February 2016

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

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

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

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

var maxSize = 30;
var minSize = 10;
var maxX = c.width;
var maxY = c.height;

function randoms() {
  var size = Math.ceil(Math.random() * maxSize);
  size = Math.max(size, minSize);
  var x = Math.floor(Math.random() * maxX);
  var y = Math.floor(Math.random() * maxY);
  var colour = '#' + Math.random().toString(16).substr(2,6);
  return {size:size, x:x, y:y, colour:colour};
}

for (var i = 0; i < 10; i++) {
  var r = randoms();
  drawFilledCircle(r.size, r.x, r.y, r.colour);
  r = randoms();
  drawSplatter(r.size, r.x, r.y, r.colour);
}
body {
  background-color:#222222;
}
<canvas id="myCanvas" width="550" height="400"></canvas>

Post Status

Asked in February 2016
Viewed 1,044 times
Voted 11
Answered 1 times

Search




Leave an answer


Quote of the day: live life