[Tutorial] How to make Game with Html5 Canvas

Chapter 1: Intro and Background

GatoMaster
2 min readDec 5, 2018

ในบทความนี้เราจะมาลองทำเกมง่ายๆ บน Html5 Canvas กัน โดย Tutorial จะแบ่งออกเป็น

5 Chapter How to make Game with Canvas

Chapter 1: Intro and Background

Chapter 2: [Tutorial] How to Move Plate

Chapter 3: [Tutorial] How to random cat

Chapter 4: [Tutorial] How to make scoring system

Chapter 5: [Tutorial] How to make Game Over

มาสร้าง Structure ของ Folder กันก่อน โดยจะแบ่งได้ตามภาพนี้

สร้าง html 5

<html>
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
</body>
</html>

เพิ่ม<canvas></canvas> ลงไปใน html กำหนดขนาดและ Style ของ Canvas

<html>
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<canvas id="canvas" width="420" height="580" style = "border: 1px solid #000;display:block; margin:0 auto;"></canvas>
</body>
</html>

จากนั้นกดเปิด html จะได้ดังรูปนี้

Background

สร้างไฟล์ JavaScripts ตั้งชื่อ Main.js

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

จากนั้นทำการดาวโหลดรูป Background และ save ไว้ที่ image folder

ดาวโหลด Background ได้ที่ Designed by Freepik

วิธีการเรียกใช้งาน Background

สร้างตัวแปร image และเรียก Path ไปยังรูปที่ต้องการ

var image = new Image();
image.src = "./image/bg1.jpg";

สร้างฟังก์ชั่น render และสั่งให้ canvas วาดรูป image ของเรา

var render = function(){
ctx.drawImage(image,0,0,canvas.width,canvas.height);
};

สร้างฟังก์ชั่น main(); เรียกใช้ฟังก์ชั่น render และทำ animation โดยการใช้ requestAnimationFrame (ส่วนถ้าใครสงสัยทำไมถึงใช้ requestAnimationFrame สามารถไปอ่านได้ที่ Click here)

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.WebkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
var main = function(){
render();
requestAnimationFrame(main);
};

เรียกใช้ฟังก์ชั่น Main();

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var image = new Image();
image.src = "./image/bg1.jpg";
var render = function(){
ctx.drawImage(image,0,0,canvas.width,canvas.height);
};
var main = function(){
render();
requestAnimationFrame(main);
};
main();

ให้ไปทำการเรียกใช้ JavaScript ใน html

<script type="text/javascript" src="./Main.js"></script>

จากนั้นให้กดเปิด html จะได้รูป Background ขึ้นมาแสดง

--

--