刚写完页面时钟,觉得还有些精力,不如更加水的来一个关于页面小球在固定边框内跳动。
由于总结了时钟的受益较多,开始的背景颜色就直接采用时钟的,直接开始进行画布的绘画。
本文的特点在于,页面中一个小球在与边框四周接触后会显示相对应的边框颜色。所以盒子的四周 我们开始设置四种颜色。
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()方法将步长进行随机分布,总得来说这个动画就相对来说较为简单。纯属娱乐!!哈哈!