Jake
Jake

Reputation: 5

Drawing circles in loop for canvas

So i would like to draw a circles in loop but when i run my code i get somthing like this:

enter image description here

It should just draw 3 circles in random places. My code is like this:

for (var i = 0; i < iloscU; i++) {
    ctx.strokeStyle = "black";
    var centreX = Math.random() * 1000;
    var centreY = Math.random() * 1000;
    var radius = 75;
    var startAngle = 0 * Math.PI / 180;
    var endAngle = 360 * Math.PI / 180;
    ctx.arc(centreX, centreY, radius, startAngle, endAngle, false);
    ctx.fillStyle = 'green';
    ctx.fill();
    ctx.stroke();
}

I know it propobly something stupid but well i dont know what :(

Upvotes: 0

Views: 2723

Answers (4)

Passerby
Passerby

Reputation: 10070

Because you're still in the same path, so canvas "line up" the points for you.

To separate, begin a new path each time you want to draw a shape, and close it when you're done:

ctx.strokeStyle="black";
ctx.fillStyle="green";
var RADIUS=75;
var START_ANGLE=0;
var END_ANGLE=2*Math.PI;
var cx,cy;
for(var i=0;i<iloscU;i++){
    cx=Math.random()*1000;
    cy=Math.random()*1000;
    ctx.beginPath();
    ctx.arc(cx,cy,RADIUS,START_ANGLE,END_ANGLE,false);
    ctx.fill();
    ctx.stroke();
    ctx.closePath();
}

JSFiddle demo

Notice that

  • In fiddle I used 500 not 1000 because the canvas in demo is only 500 width and 500 height;
  • I moved all "constants" out of loop since you don't really need to re-calculate them over and over again.

Upvotes: 3

user2808054
user2808054

Reputation: 1386

I havent got time to test this I'm afraid but try adding openPath and closePath :

for(var i=0;i<iloscU;i++){

ctx.beginPath(); // open a new path

ctx.strokeStyle = "black";
var centreX = Math.random() * 1000;
var centreY = Math.random() * 1000;
var radius = 75;

var startAngle = 0 * Math.PI/180;

var endAngle = 360 * Math.PI/180;

ctx.arc(centreX,centreY,radius,startAngle,endAngle,false);

ctx.fillStyle = 'green';
ctx.fill();
ctx.stroke();


ctx.closePath(); // close the path

}

Upvotes: 0

Paul Rad
Paul Rad

Reputation: 4882

I think your randoms are incorrects

Fiddle (your script work)

http://jsfiddle.net/BwEsr/

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

var iloscU = 3;
for(var i=0;i<iloscU;i++){

ctx.strokeStyle = "black";
var centreX = Math.random() * 500 // limit 500 because canvas width = 500;
var centreY = Math.random() * 500 // limit 500 because canvas height = 500;
var radius = 75;

var startAngle = 0 * Math.PI/180;

var endAngle = 360 * Math.PI/180;

ctx.arc(centreX,centreY,radius,startAngle,endAngle,false);

ctx.fillStyle = 'green';
ctx.fill();
ctx.stroke();

}

Upvotes: 0

user1015989
user1015989

Reputation: 316

Add ctx.beginPath(); before the ctx.arc() line.

Upvotes: 0

Related Questions