以下是 HTML5立体小球运动动画效果代码 的示例演示效果:
部分效果截图:
HTML代码(index.html):
<!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=gb2312" />
<title>HTML5立体小球运动动画效果</title>
<style type="text/css">
html,body{width:100%;height:100%;margin:0px;padding:0px;position:relative;}
canvas{background:#eee;}
</style>
<script type="text/javascript">
window.onload=function(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.translate(250,250);
context.shadowColor="#000";
//设置阴影水平偏移
context.shadowOffsetX=0;
//设置阴影竖直偏移
context.shadowOffsetY=3;
//设置阴影模糊程度
context.shadowBlur = 5;
var circles=[];
var fouse = 300;//焦距
var random=function(min,max){
return Math.floor(Math.random()*(max-min))+min;
};
var draw=function(){
context.clearRect(-250,-250,500,500);
for ( var i = 0; i < circles.length; i++) {
var circle = circles[i];
circle.x +=circle.xspeed;
if(circle.x > 250 || circle.x < -250){
circle.xspeed*=-1;
}
circle.y +=circle.yspeed;
if(circle.y > 250 || circle.y < -250){
circle.yspeed*=-1;
}
circle.z +=circle.zspeed;
if(circle.z > 600 || circle.z < -50){
circle.zspeed*=-1;
}
var scale=fouse/(fouse+circle.z);
context.save();
context.scale(scale,scale);
context.beginPath();
var radiusBg = context.createRadialGradient(circle.x,circle.y,0,circle.x,circle.y,circle.r);
radiusBg.addColorStop(0,"#cbc0f3");
radiusBg.addColorStop(1,"#06198b");
context.fillStyle=radiusBg;
context.arc(circle.x,circle.y,circle.r,0,Math.PI*2);
context.fill();
context.restore();
}
};
for(var i =0;i<10;i++){
var obj={
x:random(-250,250),
y:random(-250,250),
z:random(-50,600),
r:random(10,20),
xspeed:random(0,10),
yspeed:random(0,10),
zspeed:random(0,20)
};
circles.push(obj);
}
setInterval(function(){
draw();
},50);
};
</script>
</head>
<body>
<div style="width:500px;margin:0 auto;">
<canvas id="canvas" height="500px" width="500px"></canvas>
</div>
</body>
</html>