排版(布局)
<body>
<canvas id="cc" width="" height="">canvas>
body>
css样式
js代码
<script type="text/javascript">
var myCanvas = document.querySelector("#cc");
var ctx = myCanvas.getContext("2d");
myCanvas.width = document.documentElement.clientWidth;
myCanvas.height = document.documentElement.clientHeight;
function Ball(x,y){
this.x = x;
this.y = y;
this.r = 30;
this.color = "rgb("+Math.floor(Math.random()*255)+","+Math.floor(Math.random()*255)+","+Math.floor(Math.random()*255)+")";
this.dx = parseInt(Math.random()*15)-4;
this.dy = parseInt(Math.random()*15)-4;
ballarr.push(this);
}
Ball.prototype.reder = function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,2*Math.PI,true);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
}
Ball.prototype.update = function(){
this.x += this.dx;
this.y += this.dy;
this.r--;
if(this.r < 0){
this.godie();
}
}
Ball.prototype.godie = function(){
for(var i = 0; i < ballarr.length;i++){
if(ballarr[i] === this){
ballarr.splice(i,1);
}
}
}
var ballarr = [];
myCanvas.onmousemove = function(){
new Ball(event.clientX,event.clientY);
}
setInterval(function(){
ctx.clearRect(0,0,myCanvas.width,myCanvas.height);
for(var i = 0; i < ballarr.length; i++){
ballarr[i].update();
ballarr[i] && ballarr[i].reder();
}
},20)
</script>
效果图
