HTML5 canvas: Mutliple arc shapes with for loop

2.4k views Asked by At

Hi there my problem with the code below is the the arc is creating 1 shape not the ten specified in the for loop...

If I was to change from arc to $cd.fillRect(10,20,$x,$y); then that would create 10 different rectangles but not the arc... what am I misunderstanding here?

 
var $canvas = $('#canvas-one')[0],
    $cd;

if ($canvas.getContext) {

$cd = $canvas.getContext('2d');

for (i = 0; i <= 10; i++) {

    $cd.fillStyle = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";

    $cd.strokeStyle = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";

    var $x = 300 + Math.floor(Math.random() * 101);
    var $y = 300 + Math.floor(Math.random() * 101);
    var $radius = 0.1 + Math.floor(Math.random() * 6);

    $cd.beginPath();

    $cd.arc($x, $y, $radius, 0, Math.PI * 2, true);

}

$cd.stroke();
$cd.fill();

//$canvas.width = $canvas.height;

}

2

There are 2 answers

0
soju On

stroke and fill should be in the loop

0
Abel Gebretnsaie On

I think you forgot to multiply x with i.

for (let i = 0; i < 10; i++) {
    context.fillStyle = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";
    context.beginPath();
    context.arc(i * x, y,15, 0, 2 * Math.PI,true);
    context.fill();