canvas繪製不重合的圓
本章節分享一段程式碼例項,它實現了動態繪製圓形的效果,並且並不會出現重合的情況,準確的說相交的情況。
程式碼例項如下:
[HTML] 純文字檢視 複製程式碼執行程式碼<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <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
- canvas 繪製圓角矩形Canvas
- canvas繪製圓形框效果不填充內部Canvas
- 使用canvas繪製圓弧動畫Canvas動畫
- canvas繪製多個圓圈效果Canvas
- 微信小程式 canvas圓角矩形的繪製微信小程式Canvas
- Canvas 繪製 3d 圓柱體Canvas3D
- 使用canvas繪製圓形進度條Canvas
- html5中canvas繪製圓形HTMLCanvas
- html5中的canvas繪製橢圓的方法HTMLCanvas
- canvas繪製圓盤走動鐘錶效果Canvas
- canvas繪製圓角矩形程式碼例項Canvas
- canvas繪製橢圓效果程式碼例項Canvas
- canvas繪製圓形鐘錶程式碼例項Canvas
- canvas繪製實心圓形程式碼例項Canvas
- canvas繪製網狀圓圈程式碼例項Canvas
- HTML5 Canvas使用路徑——繪製圓形HTMLCanvas
- 原來 Canvas 也能直接繪製圓角矩形了Canvas
- Vue canvas繪製圓形進度條動畫載入VueCanvas動畫
- 【Web前端基礎知識】如何使用Canvas繪製圓形Web前端Canvas
- canvas 繪製矩形Canvas
- canvas 繪製扇形Canvas
- canvas 繪製文字Canvas
- canvas繪製動畫的技巧Canvas動畫
- canvas繪製圓形圖案程式碼示例簡單介紹Canvas
- CSS 繪製半圓CSS
- iOS 繪製圓角iOS
- canvas 繪製線條Canvas
- canvas繪製流星效果Canvas
- canvas繪製直線Canvas
- SVG <circle> 繪製圓形SVG
- SVG 繪製圓角矩形SVG
- Canvas 繪製雷達圖Canvas
- canvas 繪製立體圓環Canvas
- canvas 繪製文字詳解Canvas
- canvas 繪製矩形缺角Canvas
- canvas 繪製雙線技巧Canvas
- canvas繪製風車效果Canvas