canvas动画--五彩缤纷的小球
var canvas = document.getElementById("mycanvas");
var canvas = canvas.getContext("2d");
方法一:ES6 定义类
class Ball{
constructor(x,y,r,color,speedx,speedy){
this.x = x;
this.y = y;
this.r = r;
this.color = color;
this.speedx = speedx;
this.speedy = speedy;
}
draw(){
context.beginPath();
context.fillStyle = this.color;
context.arc(this.x,this.y,this.r,0,Math.PI*2);
context.fill();
}
move(){
this.x += this.speedx;
this.y += this.speedy;
//碰壁检测
if(this.x <= this.r || this.x >= canvas.width - this.r ){
this.speedx *= -1;
}
if(this.y <= this.r || this.y >= canvas. height - this.r){
this.speedy *= -1;
}
}
}
方法二:ES5 构造函数
function Ball(x,y,r,color,speedx,speedy){
this.x = x;
this.y = y;
this.r = r;
this.color = color;
this.speedx = speedx;
this.speedy = speedy;
}
//画球的方法
Ball.prototype.draw = function(){
context.beginPath();
context.fillStyle = this.color;
context.arc(this.x,this.y,this.r,0,Math.PI*2);
context.fill();
}
//球的移动方法
Ball.prototype.move = function(){
this.x += this.speedx;
this.y += this.speedy;
//碰壁检测
if(this.x <= this.r || this.x >= canvas.width - this.r ){
this.speedx *= -1;
}
if(this.y <= this.r || this.y >= canvas. height - this.r){
this.speedy *= -1;
}
}
实例化小球
function randNum(min,max){
return parseInt(Math.random()*(max-min)+min);
}
function randColor(){
return "rgb("+randNum(0,256)+","+randNum(0,256)+","+randNum(0,256)+")";
}
var arr = [];
for(var i=0;i<80;i++){
var r = randNum(1,50);
var x = randNum(r,canvas.width-r);
var y = randNum(r,canvas.height-r);
var speedx = randNum(1,5);
var speedy = randNum(1,5);
var colors = randColor();
var newBall = new Ball(x,y,r,colors,speedx,speedy);
arr.push(newBall);
}
function act(){
context.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<arr.length;i++){
arr[i].draw();
arr[i].move();
}
window.requestAnimationFrame(act);
}
act();