# 使用canvas做一个少女心满满的猫猫小游戏

700

### 实现

#### 使用canvas画猫猫

1. 依葫芦画瓢，模拟出二维数组，看代码：
``````const cat = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 2, 1, 0, 0, 0, 0, 0, 0, 1, 2, 1, 0, 0],
[0, 0, 1, 2, 3, 1, 1, 1, 1, 1, 1, 3, 2, 1, 0, 0],
[0, 0, 1, 2, 3, 3, 1, 1, 1, 1, 3, 3, 2, 1, 0, 0],
[0, 0, 1, 2, 1, 1, 3, 3, 3, 3, 1, 1, 2, 1, 0, 0],
[0, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 0],
[0, 0, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 0, 0],
[0, 0, 1, 3, 1, 3, 3, 3, 3, 3, 3, 1, 3, 1, 0, 0],
[0, 1, 3, 3, 1, 3, 3, 3, 3, 3, 3, 1, 3, 3, 1, 0],
[0, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 0],
[1, 3, 3, 3, 3, 3, 2, 1, 1, 2, 3, 3, 3, 3, 3, 1],
[0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];
``````
1. 模拟了一个`16*16`的二维数组后，并且分别通过`0,1,2,3`来记录不同的色彩，然后通过`canvas`来遍历数组并绘画，代码如下：
``````const _cat = this.catObject;
const colors = ['rgb(95, 205, 233)', '#333', 'rgb(214, 240, 255)', 'orange'];
for (let i = 0 ; i < _cat.length ; i ++) {
for (let j = 0 ; j < _cat[i].length; j ++) {
const c = _cat[i][j];
const color = colors[c];
this.ctx.beginPath();
this.ctx.fillStyle = color;
this.ctx.rect(j * this.width, i * this.width, Math.ceil(this.width), Math.ceil(this.width));
this.ctx.fill();
}
}
``````

#### 操作面板

``````// 设置猫咪的表情
setCat(type = 0) {
this.catObject = JSON.parse(JSON.stringify(cat));
switch (type) {
// 默认
case 0:
this.initCat();
break;
// 无奈
case 1:
this.catObject[9][5] = 1;
this.catObject[9][6] = 1;
this.catObject[9][9] = 1;
this.catObject[9][10] = 1;
this.catObject[10][4] = 3;
this.catObject[10][11] = 3;
this.initCat();
break;
}
}
``````

#### 操作优化

``````el.scrollTop = el.scrollHeight;
``````