1. 程式人生 > >canvas繪製可控制的行走的小人

canvas繪製可控制的行走的小人

素材img

在這裡插入圖片描述

程式碼

 var Person = function (ctx) {
        /*繪製工具*/
        this.ctx = ctx || document.querySelector('canvas').getContext('2d');
        /*圖片路徑*/
        this.src = 'image/04.png';
        /*畫布的大小*/
        this.canvasWidth = this.ctx.canvas.width;
        this.canvasHeight = this.ctx.canvas.
height; /*行走相關引數*/ this.stepSzie = 10; /* 0 前 1 左 2 右 3 後 和圖片的行數包含的圖片對應上*/ this.direction = 0; /*x軸方向的偏移步數*/ this.stepX = 0; /*y軸方向的偏移步數*/ this.stepY = 0; /*初始化方法*/ this.init(); }; Person.prototype.init = function () { var
that = this; /*1.載入圖片*/ this.loadImage(function (image) { /*圖片的大小*/ that.imageWidth = image.width; that.imageHeight = image.height; /*人物的大小*/ that.personWidth = that.imageWidth / 4; that.personHeight = that.imageHeight /
4; /*繪製圖片的起點*/ that.x0 = that.canvasWidth / 2 - that.personWidth / 2; that.y0 = that.canvasHeight / 2 - that.personHeight / 2; /*2.預設繪製在中心位置正面朝外*/ that.ctx.drawImage(image, 0,0, that.personWidth,that.personHeight, that.x0,that.y0, that.personWidth,that.personHeight); /*3.能通過方向鍵去控制人物行走*/ 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); /*繪圖*/ /*在精靈圖上的定位 x 索引*/ /*在精靈圖上的定位 y 方向*/ this.ctx.drawImage(image, this.index * this.personWidth,this.direction * this.personHeight, this.personWidth,this.personHeight, this.x0 + this.stepX * this.stepSzie ,this.y0 + this.stepY * this.stepSzie, this.personWidth,this.personHeight); /*如果索引超出了 變成0*/ if(this.index >= 3){ this.index = 0; } }; new Person();

效果圖

在這裡插入圖片描述