Canvas方向键控制帧动画行走

<head>
	<meta charset="utf-8" />
	<title></title>
	<style type="text/css">
		canvas {
			border: 1px solid #ddd;
			margin: 100px;
		}
	</style>
</head>

<body>
	<canvas width="600" height="400"></canvas>
	<script type="text/javascript">
		/*构造函数*/
		var Person = function(ctx) {
			this.ctx = ctx || document.querySelector("canvas").getContext("2d");
			/*图片路径*/
			this.src = "img/20181011151329.jpg";
			/*画布大小*/
			this.canvasWidth = this.ctx.canvas.width;
			this.canvasHeight = this.ctx.canvas.height;
			/*行走相关参数*/
			this.stepSize = 10;
			/*和图片的行数有关*/
			this.direction = 0;
			/*x轴方向偏移步数*/
			this.stepX = 0;
			/*y轴方向偏移步数*/
			this.stepY = 0;
			/*初始化方法*/
			this.init();
		}
		/*行为方法*/
		Person.prototype.init = function() {
			var that = this;
			/*加载图片*/
			this.loadImage(function(image) {
				/*图片的大小*/
				that.imageWidth = image.width;
				that.imageHeight = image.height;
				/*人物的大小*/
				that.personWidth = that.imageWidth / 4;
				that.personHeight = that.imageHeight / 10;
				/*图片起点*/
				that.x0 = that.canvasWidth / 2 - that.personWidth / 2;
				that.y0 = that.canvasHeight / 2 - that.personHeight / 2;
				/*默认绘制在中心位置,正面朝向外*/
				that.ctx.drawImage(image, 0, 0, that.personWidth, that.personHeight, that.x0, that.y0, that.personWidth, that.personHeight);
				/*通过方向键控制人物行走*/
				that.index = 0;
				document.onkeydown = function(e) {
					if(e.keyCode == 40) {
						/*前*/
						that.direction = 0;
						that.stepY++;
						that.drawImage(image);
					} else if(e.keyCode == 37) {
						/*左*/
						that.direction = 1;
						that.stepX--;
						that.drawImage(image);
					} else if(e.keyCode == 39) {
						/*右*/
						that.direction = 2;
						that.stepX++;
						that.drawImage(image);
					} else if(e.keyCode == 38) {
						/*后*/
						that.direction = 3;
						that.stepY--;
						that.drawImage(image);
					}
				}
			})

		}
		/*加载图片*/
		Person.prototype.loadImage = function(callback) {
			var image = new Image();
			image.onload = function() {
				callback && callback(image);
			}
			image.src = this.src;
		}
		/*绘制图片*/
		Person.prototype.drawImage = function(image) {
			this.index++;
			/*清除画布*/
			this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
			/*绘图*/
			this.ctx.drawImage(image, this.index * this.personWidth, this.direction * this.personHeight, this.personWidth, this.personHeight, this.x0+this.stepX*this.stepSize, this.y0+this.stepY*this.stepSize, this.personWidth, this.personHeight);
			if(this.index >= 3) {
				this.index = 0;
			}
		}
		/*初始化*/
		new Person();
	</script>
</body>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值