基于HTML5canvars的小游戏,HTML5之canvas简单射箭小游戏
最近折騰一個(gè)自己個(gè)人主頁(yè),無(wú)奈履歷太渣,能放在首頁(yè)的東西不多,于是想給自己的個(gè)人主頁(yè)上添加一個(gè)小游戲。遂參考了各種教程,使用HTML5的canvas元素做了一個(gè)相當(dāng)原始的東西出來(lái),效果如圖~
QQ截圖20160325110909.png
如圖所示,右邊是一個(gè)目標(biāo)靶子,當(dāng)我們點(diǎn)擊start按鈕后它會(huì)以一個(gè)特定的速度上下來(lái)回移動(dòng)。靶子動(dòng)起來(lái)之后我們點(diǎn)擊shoot按鈕就會(huì)從左邊射出一支“箭”(其實(shí)就是一條紅線啦(⊙﹏⊙))。這支箭射中靶子后根據(jù)你射中的位置有0到10十個(gè)級(jí)別的分?jǐn)?shù)。Ok,接下來(lái)是源碼。主要是在兩個(gè)循環(huán)里面移動(dòng)箭和靶子的位置,不斷調(diào)用制繪制它們的方法。然后用一個(gè)主循環(huán)不斷判定游戲是否終止。
您的瀏覽器不支持canvas,請(qǐng)使用chrome或者firefox體驗(yàn)~
Start
shoot
var canvas = document.getElementById("canvas");
var cans = canvas.getContext("2d");
cans.strokeStyle = "grey";
cans.strokeRect(0, 0, 360, 500);
cans.moveTo(0, 250);
cans.arc(0, 250, 28, 0.5 * Math.PI, 90 + Math.PI);
cans.stroke();
var targetInterval, arrowInterval;
var started = false;
var targetUp = 0;
var target = {x: 356, y: 10, w: 2, h: 160};
var arrow = {x: 1, y: 250, len: 50};
drawArrow = function () {
cans.fillStyle = 'red';
cans.fillRect(arrow.x, arrow.y, arrow.len, 1);
};
clearArrow = function () {
cans.clearRect(arrow.x, arrow.y - 1, arrow.len, 2);
};
drawTarget = function () {
cans.fillStyle = 'green';
cans.fillRect(target.x, target.y, target.w, target.h);
for (var yi = target.y, xi = target.x, hi = target.h; yi < target.y + target.h / 2; yi += 8, xi -= 2, hi -= 16) {
cans.fillRect(xi, yi, 2, hi);
}
};
clearTarget = function () {
cans.clearRect(target.x - 20, target.y, 22, target.h);
};
drawArrow();
drawTarget();
moveArrow = function () {
clearArrow();
arrow.x += 2;
drawArrow();
};
moveTarget = function () {
clearTarget();
if (targetUp == 0) {
target.y += 2;
if (target.y + target.h > 490) {
targetUp = 1;
}
} else {
target.y -= 2;
if (target.y < 10) {
targetUp = 0;
}
}
drawTarget();
};
function getScore() {
if (arrow.x + arrow.len < target.x - 2 * 9) {
return -1;
}
var yDiff = Math.abs(target.y + target.h / 2 - arrow.y);
var nCircle = Math.floor(yDiff / 8);
var tarX = target.x - 9 * 2 + 2 * nCircle;
if (arrow.x + arrow.len < tarX) {
return -1;
}
if (10 - nCircle < 0) {
return 0;
}
return 10 - nCircle;
}
startGame = function () {
clearArrow();
clearTarget();
started = true;
target.y = 10;
arrow.x = 1;
drawArrow();
drawTarget();
targetUp = 0;
targetInterval = setInterval(moveTarget, 50);
var mainInterval = setInterval(function () {
if (getScore() != -1) {
alert("you get score " + getScore());
clearInterval(arrowInterval);
clearInterval(targetInterval);
clearInterval(mainInterval);
started = false;
}
}, 10);
};
shoot = function () {
if (started) {
arrowInterval = setInterval(moveArrow, 10);
} else {
alert("you should click start first");
}
};
總結(jié)
以上是生活随笔為你收集整理的基于HTML5canvars的小游戏,HTML5之canvas简单射箭小游戏的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: nes模拟器java怎么用_nes 红白
- 下一篇: 2017年html5行业报告,云适配发布