HTML5 Canvas Game Random Image

Chapter 3: [Tutorial] How to random Cat

GatoMaster
2 min readDec 5, 2018

จาก Chapter 1&2 เราจะได้ Background และการ movement ขึ้นมาแสดงบน Canvas ได้แล้ว ส่วนใน Chapter 3 นี้เราจะมาลอง Random รูปภาพและสั่งให้ตกลงมาแบบสุ่มกัน

ให้ทำการดาวโหลดรูป แมว และนำไปไว้ที่ image folder

สามารถดาวโหลดได้ที่ My Cat

สร้าง JavaScript File ตั้งชื่อ Cat.js และสร้างฟังก์ชั่น Cat();

function Cat(canvas,x,y){
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.x = x;
this.y = y;
this.width = 50;
this.height = 50;
this.image = new Image();
}

การ Random รูปแมวนั้นจะใช้คำสั่ง Math.random() ในการสุ่ม

function Cat(canvas,x,y){
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.x = x;
this.y = y;
this.width = 50;
this.height = 50;
this.image = new Image();
this.image.src = "./image/cat"+(Math.floor((Math.random()*22))+1)+".png";
}

สร้าง Method Update และสั่งให้ แมวตกลงมา

Cat.prototype.update = function(dt) {
this.y += 100*dt;
};

สร้าง Method render

Cat.prototype.render = function(){
var ctx = this.ctx;
ctx.drawImage(this.image,this.x,this.y,this.width,this.height);
};

ทำการ Save และกลับไปที่ Main.js เพื่อเรียกใช้งาน ทำการประกาศ Array

var catsArr = [];

ไปที่ฟังก์ชั่น render ทำการสั่ง render แมว ใน loop

var render = function(){
ctx.drawImage(image,0,0,canvas.width,canvas.height);
Plate.render();
for(var i =0; i < catsArr.length; i++){
catsArr[i].render();
}
};

ไปที่ฟังก์ชั่น update โดยเราจะสั่งให้ random แมวทุกๆ 0.7 วินาที ดังนั้นให้ทำการสร้างตัวแปร Time

var time = 0;

และภายใน ฟังก์ชั่น Update ให้ทำการเขียน Scripts ให้ add แมวเพิ่มเข้าไปใน Array ทุกๆ 0.7 วินาที

สังเกตที่คำสั่ง push จะเป็นการเรียก object โดยกำหนดค่าเอาไว้แบบ Random ตำแหน่งบนหน้าจอ

var update = function(dt){
Plate.update(dt);
time += dt;
if(time >= 0.7){
time = 0;
catsArr.push(new Cat(canvas,Math.floor((Math.random()*(canvas.width-50))) ,-50))
}
canvas.setAttribute('tabindex','0');
canvas.focus();
};

จากนั้นให้ทำการเรียกใช้ Method Update ใน Cat

var update = function(dt){
Plate.update(dt);
time += dt;
if(time >= 0.7){
time = 0;
catsArr.push(new Cat(canvas,Math.floor((Math.random()*(canvas.width-50))) ,-50))
}
for(var i =0; i < catsArr.length; i++){
catsArr[i].update(dt);
}
canvas.setAttribute('tabindex','0');
canvas.focus();
};

เรียกใช้ JavaScripts บน html

<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>
<script type="text/javascript" src="./Plate.js"></script>
<script type="text/javascript" src="./Cat.js"></script>
<script type="text/javascript" src="./Main.js"></script>
</html>

กดรัน html แมวจะต้องตกลงมาแบบ Random

--

--