日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > HTML >内容正文

HTML

基于HTML5canvars的小游戏,HTML5之canvas简单射箭小游戏

發布時間:2023/12/20 HTML 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 基于HTML5canvars的小游戏,HTML5之canvas简单射箭小游戏 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

最近折騰一個自己個人主頁,無奈履歷太渣,能放在首頁的東西不多,于是想給自己的個人主頁上添加一個小游戲。遂參考了各種教程,使用HTML5的canvas元素做了一個相當原始的東西出來,效果如圖~

QQ截圖20160325110909.png

如圖所示,右邊是一個目標靶子,當我們點擊start按鈕后它會以一個特定的速度上下來回移動。靶子動起來之后我們點擊shoot按鈕就會從左邊射出一支“箭”(其實就是一條紅線啦(⊙﹏⊙))。這支箭射中靶子后根據你射中的位置有0到10十個級別的分數。Ok,接下來是源碼。主要是在兩個循環里面移動箭和靶子的位置,不斷調用制繪制它們的方法。然后用一個主循環不斷判定游戲是否終止。

您的瀏覽器不支持canvas,請使用chrome或者firefox體驗~

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");

}

};

總結

以上是生活随笔為你收集整理的基于HTML5canvars的小游戏,HTML5之canvas简单射箭小游戏的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。