面向对象其实理解起来,说容易也容易,说难也确实很难,而且,明白什么是面向对象,却未必能写出来好的代码:
下面是一个简单的例子,大家可以参考一下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
body {
text-align: center;
}
button {
margin: 80px auto 0;
padding: 5px 10px;
}
canvas {
margin: 10px auto 0;
background: #000;
}
</style>
</head>
<body>
<button>走你</button>
<button>停止</button>
<br>
<canvas height="300" width="500"></canvas>
<script>
window.onload = function(){
//UI设置
var canvas = document.getElementsByTagName('canvas')[0],
btnGo = document.getElementsByTagName('button')[0],
btnStop = document.getElementsByTagName('button')[1];
// 获取画布
var ctx = canvas.getContext("2d");
//画布尺寸
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
//变量声明
var planetArr = [];
var timer = null
//游戏设置
var playGames;
//类定义
var Planet = function (x, y, vx, vy, r) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.r = r;
};
Planet.prototype.move = function () {
this.x += this.vx;
this.y += this.vy;
if (this.x > canvasWidth - this.r) {
this.x = canvasWidth - this.r;
this.vx = -this.vx;
} else if (this.x < this.r) {
this.x = this.r;
this.vx = -this.vx;
}
if (this.y > canvasHeight - this.r) {
this.y = canvasHeight - this.r;
this.vy = -this.vy;
} else if (this.y < this.r) {
this.y = this.r;
this.vy = -this.vy;
}
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
ctx.fill();
};
//重置和重启游戏
function startGame() {
//游戏设置,初始化
var x, y, vx, vy, r, planet;
for (var i = 0; i < 100; i++) {
x = Math.random() * canvasWidth;
y = Math.random() * canvasWidth;
vx = Math.random() * 5 * (Math.random() > 0.5 ? 1 : -1);
vy = Math.random() * 5 * (Math.random() > 0.5 ? 1 : -1);
r = Math.random() * 8 + 2;
planet = new Planet(x, y, vx, vy, r);
planetArr.push(planet);
}
ctx.fillStyle = 'white';
// 游戏事件绑定
//开始游戏循环
animate();
};
//初始化游戏环境
function init() {
btnGo.onclick = function (e) {
playGames = true;
animate();
};
btnStop.onclick = function () {
playGames = false;
}
startGame();
};
//动画循环
function animate() {
//清除
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
//动画设置
for (var i = 0; i < planetArr.length; i++) {
planetArr[i].move();
}
if (playGames) {
//设置循环时间
clearTimeout(timer);
timer = setTimeout(animate, 33);
}
}
//开始游戏
init();
}
</script>
</body>
</html>