简介
canvas 是HTML5 提供的一种新标签,它可以支持 JavaScript 在上面绘画,控制每一个像素,它经常被用来制作小游戏,接下来我将用它来模仿制作一款叫flappy bird的小游戏。flappy bird(中文名:笨鸟先飞)是一款由来自越南的独立游戏开发者Dong Nguyen所开发的作品,于2013年5月24日上线,并在2014年2月突然暴红。
游戏规则
玩家只需要用一根手指来操控,点击或长按屏幕,小鸟就会往上飞,不断的点击就会不断的往高处飞。放松手指,则会快速下降。所以玩家要控制小鸟一直向前飞行,然后注意躲避途中高低不平的管子。小鸟安全飞过的距离既是得分。当然撞上就直接挂掉,只有一条命。
游戏素材
提取码:02ii
开始制作
初始化canvas画布
这里主要是创建画布,并调整画布大小,画布自适应屏幕大小。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style> body {
margin: 0;
padding: 0;
overflow: hidden;
} </style>
</head>
<body>
<canvas id="canvas">
当前浏览器不支持canvas,请更换浏览器查看。
</canvas>
<script> /** @type {HTMLCanvasElement} */
const canvas = document.querySelector('#canvas')
const ctx = canvas.getContext('2d')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
window.addEventListener('resize', () => {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
}) </script>
</body>
</html>
加载资源
图片等资源的加载是异步的,只有当所有的资源都加载完了才能开始游戏,所以这里需要对图片等资源进行统一的监控和管理。 将图片资源用json进行描述,通过fetch进行统一加载。
![](https://i-blog.csdnimg.cn/blog_migrate/9dd36ca79b66f5412cb0de790ad18074.gif)
// 资源管理器
class SourceManager {
static images = {};
static instance = new SourceManager();
constructor() {
return SourceManager.instance;}
loadImages() {
return new Promise((resolve) => {
fetch("./assets/images/image.json")
.then((res) => res.json())
.then((res) => {
res.forEach((item, index) => {
const image = new Image();
image.src = item.url;
image.onload = () => {
SourceMa