一:创建画布

<canvas width="200" height="500" id="canvas" style="border:10px solid #A2CD5A;"></canvas>
<input type="text" placeholder="难度(1-5)" id="sd">
<div id="btn">开始</div>

二:实现功能

var canvas = document.getElementById('canvas');
var cxt = canvas.getContext('2d');

// 定时器
var timer;
// 游戏是否结束
var iStop;
// 赛车
var car;
// 障碍物
var blocks;
// 障碍物速度
var speed;

// 清除画布
function erase(){
cxt.clearRect(0, 0, canvas.width, canvas.height);
}

function init(){
iStop = false;
// 赛车
car = {'x':0,'y':450,'width':50, 'height':50};
// 障碍物
blocks = [
{'x':-0,'y':-50,'width':50, 'height':50},
{'x':50,'y':-50,'width':50, 'height':50},
{'x':100,'y':-50,'width':50, 'height':50},
{'x':0,'y':250,'width':50, 'height':50},
{'x':50,'y':250,'width':50, 'height':50},
{'x':150,'y':250,'width':50, 'height':50}
];
speed = 2;
}

// 绘图
function draw(){
cxt.save();
cxt.fillRect(car.x, car.y, car.width, car.height);
for(var i=0;i<blocks.length;i++){
cxt.fillRect(blocks[i].x, blocks[i].y, blocks[i].width, blocks[i].height);
if(blocks[i].y > 400 && blocks[i].x == car.x){
iStop = true;
}
}
cxt.restore();
}

// 障碍物前进
function step(){
var _blocks = [];

for(var i=0;i<blocks.length;i++){
blocks[i].y += speed;
if(blocks[i].y < 500){
_blocks.push(blocks[i]);
}
}

if(_blocks.length == 3){
var out = Math.round(Math.random()*3);
for(var j=0; j<4; j++){
if(j != out){
_blocks.push({'x':(50*j),'y':-50,'width':50, 'height':50});
}
}
}

blocks = _blocks;
}

function drawOver() {
cxt.save();
cxt.font="20px Verdana";
cxt.fillStyle = 'yellow';
cxt.fillText('游戏结束!', 75, 200);
cxt.restore();
}

// 键盘控制赛车左右(<-、->)运动
var last = new Date();
document.onkeydown = (function(e){
var now = new Date();
if(now.getTime() - last.getTime() < 100){
return;
}
last = now;
switch(e.which){
case 39:
if(car.x < 150){
car.x += 50;
}
break;
case 37:
if(car.x > 0){
car.x -= 50;
}
break;
}
});

window.requestAnimationFrame =
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;

window.cancelRequestAnimationFrame =
window.cancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame;

function animate() {
erase();
draw();
step();
if(iStop){
cancelRequestAnimationFrame(timer);
drawOver();
}else{
timer = requestAnimationFrame(animate);
}
}

//animate();

document.querySelector('#btn').onclick = function(){
if(this.innerHTML == '开始'){
init();

var s = document.querySelector('#sd').value;
if(s != ''){
speed = parseInt(s);
}

animate();
this.innerHTML = '结束';
}else{
cancelRequestAnimationFrame(timer);
this.innerHTML = '开始';
}
}

Posted on 2017-11-16 22:27  LY_Young  阅读(588)  评论(0编辑  收藏  举报