Reputation: 5
So i would like to draw a circles in loop but when i run my code i get somthing like this:
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
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();
}
Notice that
Upvotes: 3
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
Reputation: 4882
I think your randoms are incorrects
Fiddle (your script work)
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