01-移动精灵-面向对象版本.htm
<body>
<article>
<canvas height="200" width="400" id="genius"></canvas>
<div>
<button id="forward">forward</button>
<button id="right"> right</button>
<button id="back">back</button>
<button id="left">left</button>
</div>
</article>
<script src="01-移动精灵-面向对象版本.js"></script>
</body>
01-移动精灵-面向对象版本.js
Genius 类的封装
var Genius = function (option) {
Genius.prototype._init_(option);
}
Genius.prototype = {
constructor: Genius,
// 把对象的初始化代码都放在这里,把它需要用到的所有变量都绑定到它的原型上.
_init_: function (option) {
this.img = option.img;
this.rowIndex = option.rowIndex;
this.columnIndex = option.columnIndex;
this.frame = option.frame;
this.singleWidth = option.singleWidth;
this.singleHeight = option.singleHeight
},
// 由于js面向对象的特点,获取会从父对象的prorotype里面获取,但是设置只会设置自己的
draw: function (ctx, direction) {
window.clearInterval(this.intervalId);
this.rowIndex = direction;
// 一定要设置,因为在setInterval里面,this指的就是window变量
var that = this;
this.intervalId = setInterval(function () {
// 在没绘制一张小图片之前,都要清空之前绘制的图片,这样才能显示出动画效果来,
ctx.clearRect(10, 10, that.singleWidth, that.singleHeight);
// 在大图上剪切绘制绘制
ctx.drawImage(that.img, that.columnIndex * that.singleWidth, that.rowIndex * that.singleHeight, that.singleWidth, that.singleHeight, 10, 10, that.singleWidth, that.singleHeight);
that.columnIndex++;
that.columnIndex %= 4;
}, 1000 / that.frame);
}
}
window.onload = function () {
var ctx = document.getElementById('genius').getContext('2d');
var oringinImg = new Image();
oringinImg.src = "./img/DMMban.png";
var genius;
oringinImg.onload = function () {
// 实例化构造一个对象
genius = new Genius({
img: oringinImg,
rowIndex: 0,
columnIndex: 0,
frame: 6,
singleWidth: 40,
singleHeight: 65
});
// 调用Genius的prototype里面的draw方法.
genius.draw(ctx, 0);
}
document.querySelector('#forward').addEventListener('click', () => {
genius.draw(ctx, 0);
});
document.querySelector('#left').addEventListener('click', () => {
genius.draw(ctx, 1);
});
document.querySelector('#right').addEventListener('click', () => {
genius.draw(ctx, 2);
});
document.querySelector('#back').addEventListener('click', () => {
genius.draw(ctx, 3);
});
};
这是效果图
嗯 canvas绘制动画帧就到这里,下一篇Canvas(三) konva 将会介绍canvas的旋转和konva库.
由于本人水平有限,如有错误,如果错误,望不吝赐教.
最后特别感谢恩师蒋坤老师(jk)对我的知识学习和人生引导的极大帮助,非常感谢他.
另 由于现任公司没有适合我的岗位,想求职一份,职位: 前端开发. 我的邮箱 mymeat@126.com.
posted @