剛寫完頁面時鐘,覺得還有些精力,不如更加水的來一個關於頁面小球在固定邊框內跳動。
由於總結了時鐘的受益較多,開始的背景顏色就直接採用時鐘的,直接開始進行畫布的繪畫。
本文的特點在於,頁面中一個小球在與邊框四周接觸後會顯示相對應的邊框顏色。所以盒子的四周 我們開始設置四種顏色。
border-top:2px solid red;
border-bottom: 2px solid green;
border-left:2px solid yellow;
border-right:2px solid blue;
這裏正是開始設置小球頁面動畫。首先得進行屬性的初始化。
<span style="white-space:pre"> </span>//初始定義動畫對象
<span style="white-space:pre"> </span>var animation={};
<span style="white-space:pre"> </span>//動畫每次移動x方向位移
animation.Xstep=2;
<pre name="code" class="html"><span> </span>//動畫每次移動y方向位移
animation.Ystep=-2;
<pre name="code" class="html"><span> </span>//小球半徑
animation.radius=15;
<pre name="code" class="html"><span> </span>//小球初始顏色白色
animation.color="white";
<pre name="code" class="html"><span> </span>//畫布動畫時間ms
animation.delay= 10;
<pre name="code" class="html"><span> </span>//小球初始位置
animation.x=100;animation.y=100;
<pre name="code" class="html"> //定時器
<span style="white-space:pre"> </span>animation.interval=null;
接下來就是動畫方法的設計。調用restore和save方法進行繪畫的更新。 <span style="white-space:pre"> </span>animation.draw=function(){
var plo = document.getElementById("boxer");
var width = plo.getAttribute("width");
var height = plo.getAttribute("height");
var ctx = plo.getContext("2d");
//保存狀態
ctx.save();
//清空畫布
ctx.clearRect(0,0,width,height);
//更新圓心座標
this.update(width,height);
//更新小球顏色
ctx.fillStyle = this.color;
//移動圓心座標
ctx.translate(this.x,this.y);
//繪畫填充小球
ctx.beginPath();
ctx.arc(0,0,15,0,2*Math.PI,true);
ctx.fill();
//恢復狀態
ctx.restore();
<span style="white-space:pre"> </span>};
當動畫完善之後,發現不能再邊界進行反彈和顏色的改變,此時,需要定義一個update方法進行邊界的判斷與小球填充色的改變。
<span style="white-space:pre"> </span>animation.update=function(width,height){
this.x+=this.Xstep;
this.y+=this.Ystep;
if (this.x<this.radius)
{
this.x = this.radius;
this.Xstep = -this.Xstep;
this.color = "yellow";
}
if (this.x+this.radius>width)
{
this.x = width-this.radius;
this.Xstep = -this.Xstep;
this.color = "blue";
}
if (this.y<this.radius)
{
this.y = this.radius;
this.Ystep = -this.Ystep;
this.color = "red";
}
if (this.y+this.radius>height)
{
this.y = height-this.radius;
this.Ystep = -this.Ystep;
this.color = "green"
}
};
這個方法的設計很簡單,一遍就過去了,不再贅述這個。如果進行調用setInterval("animation.draw()",this.delay)基本可以看到一個在四周進行碰撞反彈的動畫了。爲了豐富一些內容,在後面我們可以添加兩個動作按鈕start和pause進行開始和暫停的控制。
這裏pause方法只需要將定時器置爲null即可暫停動畫。
animation.pause=function(){
clearInterval(this.interval);};
start方法則可以先調用draw方法即可進行開始動畫。爲了初始化,首先將動畫進行暫停,然後通過onclick時間監聽動作按鈕實現最終的動畫。
從左到右,至上而下可發現分別與上邊界、右邊界、下邊界、左邊界接觸後小球的顏色改變。
最後因爲採用的偏移步長固定,我們也可以調用Math.random()方法將步長進行隨機分佈,總得來說這個動畫就相對來說較爲簡單。純屬娛樂!!哈哈!