javascript实现画不相交的圆
更新时间:2015年04月07日 10:08:10 投稿:hebedich
这篇文章主要介绍了javascript实现画不相交的圆,这个也是阿里巴巴的笔试题,只不过忘记当时是不是要求必须用canvas来实现,下篇文章再写吧。
效果

html代码
复制代码 代码如下:
<canvas id="my_canvas" width="500" height="400">
your browser does not support canvas
</canvas>
<button id="my_btn">Another Circle</button>
javascript代码
复制代码 代码如下:
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 is no space 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;
}
}
以上所述就是本文的全部内容了,希望能够对大家熟练掌握javascript有所帮助。
相关文章
javascript如何在foreach循环完成之后执行一个回调函数
forEach()是前端开发中操作数组的一种方法,主要功能是遍历数组,其实就是 for 循环的升级版,下面这篇文章主要给大家介绍了关于javascript如何在foreach循环完成之后执行一个回调函数的相关资料,需要的朋友可以参考下2023-11-11
underscore之Collections_动力节点Java学院整理
underscore为集合类对象提供了一致的接口。集合类是指Array和Object,暂不支持Map和Set。下面通过本文给大家分享underscore之Collections的相关知识,需要的的朋友参考下吧2017-07-07
UniApp使用manifest.json应用配置的超详细教学
这篇文章主要给大家介绍了关于uni-app应用配置manifest.json最全最详细配置,manifest.json文件是应用的配置文件,用于指定应用的名称、图标、权限等,文中通过代码介绍的非常详细,需要的朋友可以参考下2024-01-01


最新评论