国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

javascript實現畫不相交的圓

2019-11-20 12:45:08
字體:
來源:轉載
供稿:網友

效果

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有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 石景山区| 江阴市| 固始县| 兖州市| 陆河县| 泸州市| 喀喇沁旗| 莆田市| 金昌市| 东明县| 汉源县| 兴国县| 莲花县| 辛集市| 益阳市| 沙河市| 重庆市| 峨山| 娄底市| 织金县| 丰宁| 广宗县| 孟州市| 临武县| 新余市| 芜湖市| 舒城县| 石景山区| 定兴县| 台中县| 揭阳市| 建阳市| 侯马市| 永登县| 商水县| 太原市| 克东县| 孙吴县| 宁河县| 荔波县| 阳信县|