canvas绘制不重合的圆
分类:实例代码
canvas绘制不重合的圆属于前端实例代码,有关更多实例代码大家可以查看。
本章节分享一段代码实例,它实现了动态绘制圆形的效果,并且并不会出现重合的情况,准确的说相交的情况。
代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>前端教程网</title> <script> window.onload=function(){ 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; 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){ alert("no more circle"); return false; } make_circle(); } } //test if the new circle intersects with the others function test1(circle){ 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; } } } </script> </head> <body> <canvas id="my_canvas" width="500" height="400">不支持canvas</canvas> <button id="my_btn">创建一个圆</button> </body> </html>
canvas绘制不重合的圆,这样的场景在实际项目中还是用的比较多的,关于canvas绘制不重合的圆就介绍到这了。