[英]How to draw circle at random position in between of two circles?
我有兩個圈子。 一種半徑為150,另一種半徑為350。 我想在150-350半徑的空間之間放置圓數。 它不應該在已經放置的其他圓上過度放置(覆蓋)。 應該在每次刷新時隨機放置它。 可以請一個人給我關於如何在畫布上執行此操作的想法/邏輯。 的JavaScript。
[編輯]
至於繪制實際圖像,這取決於您,但是這是您放置圓圈的方式:
首先,隨機選擇一個介於0°和360°之間的Θ。
然后為您的小圓圈選擇半徑r1
,介於0和50之間(“軌跡”的100像素寬度的一半)。
然后在150 + r1
和350- r1
之間選擇一個中心位置r2
。
現在在由(Θ, r2
)在極坐標中給定的位置繪制一個圓半徑r1
。
演示: http : //jsfiddle.net/m1erickson/aGq8p/
這里的技巧是創建隨機圓,但也要確保它們不與先前創建的圓重疊。
這是帶注釋的代碼:
function randomCircle(){
// define random radius
var radius=minCircle+Math.random()*(maxCircle-minCircle);
// define random distance between inner/outer rings
var distFromCenter=innerRadius+radius+Math.random()*(outerRadius-innerRadius-radius*2);
// define random angle
var angle=Math.random()*PI2;
// calculate the x,y of the defined circle
var x=cx+distFromCenter*Math.cos(angle);
var y=cy+distFromCenter*Math.sin(angle);
// check this new circle versus all previous random circles for a collision
var hit=false;
for(var i=0;i<randomCircles.length;i++){
var circle=randomCircles[i];
var dx=circle.cx-x;
var dy=circle.cy-y;
var r=circle.radius+radius;
if(dx*dx+dy*dy<=r*r){
hit=true;
}
}
// if no collision occurred, add this new circle to the existing circles array
if(!hit){
var color=randomColor();
randomCircles.push({cx:x,cy:y,radius:radius,color:color});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.