拿昨天的動畫 sprite function 示範用 prototype 和 es6 的 class 重構
步驟
1.建立時呼叫⺟類別 (初始化母類別屬性)
2.⼦類別新增繼承 prototype (讓子類別可以使用母類別的⽅法)
3.將建構函數指向自己 (將物件建構的函數指向最底層類別)
sprite.prototype.update = function() {
this.tickCount += 1;
if (this.tickCount > this.ticksPerFrame) {
this.tickCount = 0;
// If the current frame index is in range
if (this.frameIndex < this.numberOfFrames - 1) {
// Go to the next frame
this.frameIndex += 1;
} else {
this.frameIndex = 0;
}
}
};
sprite.prototype.render = function() {
// Clear the canvas
this.context.clearRect(0, 0, this.width, this.height);
// Draw the animation
this.context.drawImage(
this.image,
(this.frameIndex * this.width) / this.numberOfFrames,
0,
this.width / this.numberOfFrames,
this.height,
0,
0,
this.width / this.numberOfFrames,
this.height
);
};
// Create sprite
var Hedgehog = function() {
// 初始化
sprite.call(this, {
context: canvas.getContext("2d"),
width: 1615,
height: 351,
image: hedgehogImage,
numberOfFrames: 6,
ticksPerFrame: 10
});
};
關鍵於
// Hedgehog 可以使用 sprite 的方法
Hedgehog.prototype = Object.create(sprite.prototype);
// Hedgehog 把 constructor 指向自己的 constructor
Hedgehog.prototype.constructor = Hedgehog.constructor;
再來就是 es6 的 class ,你會發現它真的是語法糖,是利用 [[Prototype]] 委派機制來實作的
使⽤class糖衣簡化語法
class sprite {
constructor({
context,
width,
height,
image,
ticksPerFrame,
numberOfFrames
}) {
this.context = context;
this.width = width;
this.height = height;
this.image = image;
this.frameIndex = 0;
this.tickCount = 0;
this.ticksPerFrame = ticksPerFrame || 0;
this.numberOfFrames = numberOfFrames || 1;
}
update = () => {
this.tickCount += 1;
if (this.tickCount > this.ticksPerFrame) {
this.tickCount = 0;
// If the current frame index is in range
if (this.frameIndex < this.numberOfFrames - 1) {
// Go to the next frame
this.frameIndex += 1;
} else {
this.frameIndex = 0;
}
}
};
render = () => {
// Clear the canvas
this.context.clearRect(0, 0, this.width, this.height);
// Draw the animation
this.context.drawImage(
this.image,
(this.frameIndex * this.width) / this.numberOfFrames,
0,
this.width / this.numberOfFrames,
this.height,
0,
0,
this.width / this.numberOfFrames,
this.height
);
};
}
再來只要
// Create sprite
hedgehog = new sprite({
context: canvas.getContext("2d"),
width: 1615,
height: 351,
image: hedgehogImage,
numberOfFrames: 6,
ticksPerFrame: 10
});
即可使用 sprite 這個 class
我的刺蝟依舊可以行走~
若有錯誤的觀念或是資料授權有問題,再煩請通知我,謝謝