課程
/前端開(kāi)發(fā)
/Html5
/Canvas繪圖詳解
我想問(wèn)一下老師,如何解決層疊問(wèn)題
2015-05-21
源自:Canvas繪圖詳解 5-1
正在回答
試著做了下 ,不知道有沒(méi)有什么問(wèn)題
<!DOCTYPE?html> <html> <head> <meta?charset="utf-8"?/> <title></title> </head> <body> <canvas?id="canvas"?style="display:?block;?margin:?0?auto;?border:?1px?solid?#999;"></canvas> <script?type="text/javascript"> window.onload=function(){ var?canvas=document.getElementById("canvas"); canvas.width=1200; canvas.height=600; var?ctx=canvas.getContext("2d"); var?skyStyle=ctx.createLinearGradient(0,0,0,canvas.height); skyStyle.addColorStop(0.0,'black'); skyStyle.addColorStop(1.0,'#035') ctx.fillStyle=skyStyle; ctx.fillRect(0,0,canvas.width,canvas.height); fill(canvas.width,canvas.height,5,ctx); } function?fill(w,h,r,ctx){ var?_data=[]; //儲(chǔ)存星星的坐標(biāo),用于比較 var?abc; for(var?i=0;i<200;i++){ var?R=Math.round(Math.random()*5)+r; var?x=Math.round(Math.random()*(w-2*R))+R; var?y=Math.round(Math.random()*(h*0.65-2*R))+R; var?rote=Math.round(Math.random()*360); ? //判斷條件,若當(dāng)前位置與其他星星不重合就會(huì)返回其他星星的個(gè)數(shù) abc=function(){ var?a=0; for(var?j=0;j<_data.length;j++){ if(!((_data[j][0]+_data[j][2]>x&&x>_data[j][0]-_data[j][2])&&(_data[j][1]+_data[j][2]>y&&y>_data[j][1]-_data[j][2]))){ a+=1; } } return?a; } //滿足條件就會(huì)重新隨機(jī)坐標(biāo), 注意:畫布太小星星太多可能會(huì)造成死循環(huán) while(abc()!=_data.length){ x=Math.round(Math.random()*(w-2*R))+R; y=Math.round(Math.random()*(h*0.65-2*R))+R; } _data.push([x,y,R]); //把當(dāng)前的坐標(biāo)和半徑添加進(jìn)去,完全分離則設(shè)置為2*R drawStart(x,y,R,rote,ctx); } } //繪制圖形 function?drawStart(x,y,R,rote,ctx){ ctx.lineWidth=R/(R*10); ctx.lineJoin="round"; ctx.fillStyle="yellow"; ctx.strokeStyle="yellow"; ctx.save(); ctx.translate(x,y); ctx.rotate(rote/180*Math.PI); ctx.scale(R,R); startPath(ctx); ctx.fill(); ctx.stroke(); ctx.restore(); } //繪制路徑 function?startPath(ctx){ ctx.beginPath(); for(var?i=0;i<5;i++){ ctx.lineTo(Math.cos((18+i*72)/180*Math.PI),-Math.sin((18+i*72)/180*Math.PI)); ctx.lineTo(Math.cos((54+i*72)/180*Math.PI)*0.5,-Math.sin((54+i*72)/180*Math.PI)*0.5); } ctx.closePath(); } </script> </body> </html>
舉報(bào)
Canvas系列教程第二課,詳解Canvas各接口,讓同學(xué)徹底掌握Canvas繪圖
1 回答關(guān)于星星重疊問(wèn)題
3 回答如何讓背景圖隨 cancas 的移動(dòng)而移動(dòng)
1 回答如果鼠標(biāo)位置是重疊的位置,怎么只讓最上層的選中呢?
3 回答畫布重疊 兩個(gè)canvas怎么重疊在一起
1 回答如何處理星星不重疊呢?
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號(hào)-11 京公網(wǎng)安備11010802030151號(hào)
購(gòu)課補(bǔ)貼聯(lián)系客服咨詢優(yōu)惠詳情
慕課網(wǎng)APP您的移動(dòng)學(xué)習(xí)伙伴
掃描二維碼關(guān)注慕課網(wǎng)微信公眾號(hào)
2015-07-18
試著做了下 ,不知道有沒(méi)有什么問(wèn)題