Effect
HTML code
Copy Code code as follows:
<canvas id= "My_canvas" width= "height=" >
Your browser does not support canvas
</canvas>
<button id= "my_btn" >another circle</button>
JavaScript code
Copy Code code as follows:
var Context=document.getelementbyid ("My_canvas");
Context=context.getcontext ("2d");
var circles=[];
var width=500;
var height=400;
var max_radius=30;
var min_radius=20;
var count=0;
Window.onload=function () {
var Btn=document.getelementbyid ("My_btn");
Btn.onclick=function () {
var time=new Date ();
Start=time.gettime ();
Make_circle ();
}
}
function Circle (x,y,r,color) {
This.x=x;
This.y=y;
This.r=r;
This.color=color;
}
function Make_circle () {
var X=math.floor (Math.random () *width) +1;
var Y=math.floor (Math.random () *height) +1;
var R=math.floor (Math.random () * (Max_radius-min_radius)) +min_radius;
var color= "RGB (" + (Math.floor (Math.random () *256)) + "," + (Math.floor (Math.random () *256)) + "," + (Math.floor ( Math.random () *256)) + ")";//make different color
var circle=new circle (X,y,r,color);
if (Test1 (circle) &&test2 (circle)) {
Circles.push (circle);
Context.strokestyle=color;
Context.beginpath ();
Context.arc (x,y,r,0,math.pi*2,true);
Context.closepath ();
Context.stroke ();
count=0;
}
else{
count++;
if (count>10000) {//if It loops too many times,we can assume that there are no spaces for new circle
Alert ("No More Circle");
return false;
}
Make_circle ();
}
}
function Test1 (circle) {//test If the new circle intersects with the others
var len=circles.length;
for (Var i=0;i<len;i++) {
var x1=circles[i].x;
var y1=circles[i].y;
var r1=circles[i].r;
var x2=circle.x;
var y2=circle.y;
var R2=CIRCLE.R;
if ((x1-x2) * (X1-X2) + (y1-y2) * (Y1-y2) < (R2+R1) * (R2+R1)) {
return false;
}
}
return true;
}
function Test2 (circle) {//test If the new circle Touchs the border
if ((CIRCLE.X+CIRCLE.R) >width| | (CIRCLE.Y+CIRCLE.R) >height| | (CIRCLE.X-CIRCLE.R) <0| | (CIRCLE.Y-CIRCLE.R) <0) {
return false;
}
else{
return true;
}
}
The above is the entire content of this article, I hope to be proficient in mastering JavaScript help.