各位大神,誰(shuí)可以幫幫小妹看看這段代碼哪出錯(cuò)了,十分感謝!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>[有問題???]改寫后的繪制200個(gè)隨機(jī)的五角星</title>
</head>
<body>
<canvas id="canvas" style="margin:auto;top:0;left:0;bottom:0;right:0;position:absolute;">當(dāng)前瀏覽器不支持,請(qǐng)更換瀏覽器</canvas>
<script>
window.onload=function()
{
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
canvas.width=800;
canvas.height=800;
? ? context.fillStyle="black";
context.fillRect(0,0,canvas.width,canvas.height);
//繪制200個(gè)星星
for(var i=0;i<200;i++)
{
? var r=Math.random()*10+10;//產(chǎn)生一個(gè)5-15之間的隨機(jī)數(shù),Math.random是產(chǎn)生一個(gè)0-1之間的數(shù)
? var x=Math.random()*canvas.width;
? var y=Math.random()*canvas.height;
? var a=Math.random()*360;//產(chǎn)生一個(gè)隨機(jī)的角度
? drawStar(context,x,y,a);//進(jìn)行五角星函數(shù)的調(diào)用400、400控制星星的位移,R,r控制星星的大小
}
}
//自定義一個(gè)繪制五角星的函數(shù),使用時(shí)直接調(diào)用(使得繪制五角星函數(shù)化)
function drawStar(cxt,x,y,rot)
{
cxt.save();
? ? starPath(cxt);
cxt.translate(x,y);
cxt.rotate(rot/180*Math.PI);
?
? ?
?
? ? cxt.lineWidth=1;
cxt.strokeStyle="blue";
cxt.fillStyle="white";
cxt.lineJoin="round";
cxt.fill();
cxt.stroke();
cxt.restore();
}
//繪制標(biāo)準(zhǔn)五角星
function starPath(cxt)
{
cxt.beginPath();
//通過對(duì)五角星的十個(gè)頂點(diǎn)的分析,得出以下(300為大圓半徑,150為小圓半徑)
for(var i=0;i<5;i++)
{
//最開始為18度,180是JS中是弧度制,400表示使五角星在中間,-rot表示順時(shí)針轉(zhuǎn)30度,繪制五角星時(shí)是逆時(shí)針繪制的,所以順時(shí)針轉(zhuǎn)的話減相應(yīng)角度,lineTo的縱坐標(biāo)是負(fù)的,因?yàn)镴S中Y軸是向下的。
? ? ? ? cxt.lineTo(Math.cos((18+i*72)/180*Math.PI)*20,
? ? ? ? -Math.sin((18+i*72)/180*Math.PI)*20);
cxt.lineTo(Math.cos((54+i*72)/180*Math.PI)*0.5*20,
? ? ? ? -Math.sin((54+i*72)/180*Math.PI)*0.5*20);
}
cxt.closePath();
}
</script>
</body>
</html>
2015-08-21
?starPath(cxt);
cxt.translate(x,y);
cxt.rotate(rot/180*Math.PI);
應(yīng)該是先圖形變換,再開始畫星星:
cxt.translate(x,y);
cxt.rotate(rot/180*Math.PI);
starPath(cxt);
2015-08-31
lublank解釋的應(yīng)該是對(duì)的
2015-06-23
這好坑啊 ?你把canvas 的絕對(duì)定位去掉 再試試~?。?!
2015-06-05
這是js?把問題標(biāo)簽弄到j(luò)s那邊吧,那樣多點(diǎn)人知道滴
2015-06-02
額,沒用過canvas,趕快去學(xué)習(xí)下- -!
2015-06-02
根本看不懂