[英]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: 所以我想画一个圈,但是当我运行我的代码时,我会得到这样的东西:
It should just draw 3 circles in random places. 它应该只在随机位置绘制3个圆圈。 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 :( 我知道这很愚蠢,但我不知道是什么:(
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 注意
Add ctx.beginPath();
添加
ctx.beginPath();
before the ctx.arc()
line. 在
ctx.arc()
行之前。
I think your randoms are incorrects 我认为您的随机数是不正确的
Fiddle (your script work) 小提琴(您的剧本)
http://jsfiddle.net/BwEsr/ 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();
}
I havent got time to test this I'm afraid but try adding openPath and closePath : 恐怕我没有时间进行测试,但是尝试添加openPath和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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.