来个炫酷一点的, 但代码比较简单的例子, 主要是最近学习canvas的一个小小的总结...
还是以前的样子, 因为代码不长, 所以就css(头部), html(中部)和js(尾部)连在一起写了...
<!DOCTYPE html>
<html>
<head>
<title>Canvas element size: 600 x 300, Canvas drawing surface size: 600 x 300</title>
<style>
body{
margin: 20px auto;
width: 960px;
background: black;
text-align: center;
}
#bt{
/*position: absolute;*/
padding: 0px 30px 0px 30px;
border-radius: 10px;
background: rgba(255,255,255,0.7);
float:left;
margin-bottom: 20px;
width: 70px;
}
#bt:hover{
background: orange;
}
a{
text-decoration: none;
color: white;
display: block;
}
</style>
</head>
<body>
<div style="float:left">
<a href='#' οnclick="display()"><div id='bt'><h2>start</h2></div></a>
<a href='#' οnclick="stop()"><div id='bt'><h2>stop</h2></div></a>
<a href='#' οnclick="back()"><div id='bt'><h2>back</h2></div></a>
</div>
<canvas id='canvas' width="700px" height="700px">
canvas not support
</canvas>
</body>
<script>
var color=['#0cf','#FFD39B','#FFE4E1','#FFEBCD','#33ff00','yellow']
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var ball=[];
var tot=50;
var timer;
for (var i=0;i<tot;i++){
ball[i]={
locx:100,
locy:100,
speed:Math.random()*3+1,
color:color[~~(Math.random()*6)],
angle:Math.PI*2*Math.random(),
radius:Math.random()*45+10,
dirx:1,
diry:1
}
// alert(ball[i].angle)
}
context.beginPath();
context.fillStyle="white";
context.rect(0,0,canvas.width,canvas.height);
context.fill();
function display(){
ball.forEach(function(b){
//这里也要来100个beginPath....
//还有,不能用this
context.beginPath();
context.fillStyle=b.color;
context.arc(b.locx,b.locy,b.radius,0,Math.PI*2,true);
context.fill();
});
timer=setInterval(function(){
context.fillStyle="white";
context.rect(0,0,canvas.width,canvas.height);
context.fill();
ball.forEach(function(b){
var tmp;
//撞墙检测之x轴....
tmp=b.locx+b.speed*Math.cos(b.angle)*b.dirx+b.radius;
if (tmp<=canvas.width&&tmp>=0){
tmp=b.locx+b.speed*Math.cos(b.angle)*b.dirx-b.radius;
}
if (tmp>canvas.width||tmp<0) {
b.dirx=-b.dirx;
}
b.locx+=b.speed*Math.cos(b.angle)*b.dirx;
//撞墙检测之y轴....
tmp=b.locy+b.speed*Math.sin(b.angle)*b.diry+b.radius;
if (tmp<=canvas.height&&tmp>=0){
tmp=b.locy+b.speed*Math.sin(b.angle)*b.dirx-b.radius;
}
if (tmp>canvas.height||tmp<0) {
b.diry=-b.diry;
}
b.locy+=b.speed*Math.sin(b.angle)*b.diry;
context.beginPath();
context.fillStyle=b.color;
context.arc(b.locx,b.locy,b.radius,0,Math.PI*2,true);
context.fill();
})
},1000/60)
}
function stop(){
clearInterval(timer);
}
function back(){
ball.forEach(function(b){
b.dirx=-b.dirx;
b.diry=-b.diry;
})
}
</script>
</html>
运行效果:
更多实际运行的动态效果请点击:在线演示