為什么我加了旋轉(zhuǎn)五角星就跑到黑布外面去了呢?
var searchlight={x:400,y:400,radius:150,vx:Math.random()*5+10,vy:Math.random()*5+10};
var rot=0;
window.onload=function()
{
var canvas=document.getElementById('canvas');
canvas.width=800;
canvas.height=800;
if(canvas.getContext('2d'))
{
var context=canvas.getContext('2d');
}
else
{
alert('該瀏覽器不支持!');
}
setInterval(function(){
draw(context);
update(canvas.width,canvas.height);
},40);
};
function draw(cxt)
{
var canvas=cxt.canvas;
cxt.clearRect(0,0,canvas.width,canvas.height);
cxt.save();
cxt.beginPath();
cxt.fillStyle='black';
cxt.fillRect(0,0,canvas.width,canvas.height);
cxt.save();
//cxt.arc(searchlight.x,searchlight.y,searchlight.radius,0,2*Math.PI);
//cxt.rotate(rot/180*Math.PI);
drawstar(cxt,searchlight.x,searchlight.y,searchlight.radius);
cxt.fillStyle='#fff';
cxt.fill();
cxt.restore();
cxt.clip();
cxt.font='bold 150px Arial';
cxt.textAlign='center';
cxt.textBaseline='middle';
cxt.fillStyle='#058';
cxt.fillText('CANVAS',canvas.width/2,canvas.height/4);
cxt.fillText('CANVAS',canvas.width/2,canvas.height/2);
cxt.fillText('CANVAS',canvas.width/2,canvas.height/4*3);
cxt.restore();
}
//星星
function drawstar(cxt,x,y,r)
{
cxt.beginPath();
for(var i=0;i<5;i++)
{
cxt.lineTo(Math.cos((18+i*72)/180*Math.PI)*r+x,-Math.sin((18+i*72)/180*Math.PI)*r+y);
cxt.lineTo(Math.cos((54+i*72)/180*Math.PI)*r*0.5+x,-Math.sin((54+i*72)/180*Math.PI)*r*0.5+y);
}
cxt.closePath();
}
//碰撞檢測
function update(width,height)
{
rot += 1;
searchlight.x+=searchlight.vx;
searchlight.y+=searchlight.vy;
if(searchlight.x-searchlight.radius<=0)
{
searchlight.vx=-searchlight.vx;
searchlight.x=searchlight.radius;
}
if(searchlight.x+searchlight.radius>=width)
{
searchlight.vx=-searchlight.vx;
searchlight.x=width-searchlight.radius;
}
if(searchlight.y-searchlight.radius<=0)
{
searchlight.vy=-searchlight.vy;
searchlight.y=searchlight.radius;
}
if(searchlight.y+searchlight.radius>=height)
{
searchlight.vy=-searchlight.vy;
searchlight.y=height-searchlight.radius;
}
}
2016-02-01
不好意思,剛剛沒有看清楚你注視了代碼,重新答一次。drawstar這個函數(shù)的功能是根據(jù)指定的上下文在特定的位置繪制特定大小的的星星。根據(jù)老師前面的例子,我們最好只是規(guī)劃出一個基本圖形的單位路徑。具體的位置變換,旋轉(zhuǎn),縮放都交給外部進(jìn)行。出錯的原因是在外部你進(jìn)行了旋轉(zhuǎn),在內(nèi)部進(jìn)行了位移,外部的旋轉(zhuǎn)改變了里面的坐標(biāo)系。將以上的代碼改為如下:
2016-02-01
試了下你的代碼,沒有問題啊??赡苁歉叨仍O(shè)置的大了點(diǎn)導(dǎo)致屏幕出現(xiàn)了滾動條,你會發(fā)現(xiàn)星星的一部分跑到了黑布的外側(cè),你可以拖動滾動條看一下其實(shí)星星并沒有到黑布非外面,你可以試試適當(dāng)設(shè)置小一點(diǎn)的高度,比如600就非常完美了。
2016-01-18
會不會是瀏覽器兼容問題