Canvas生成像素头像

2021/1/18 Vue
Your browser does not support the HTML5 canvas tag.
重新生成

# Avatar组件

<template>
  <div class="avatar-container">
    <canvas
      id="myCanvas"
      width="100"
      height="100"
    >
      Your browser does not support the HTML5 canvas tag.
    </canvas>
    <div
      class="button"
      @click="createAvatar"
    >
      重新生成
    </div>
  </div>
</template>

<script>
import Avatar from './avatar';

export default {
  name: 'BlogAvatar',
  data() {
    return {};
  },
  mounted() {
    this.createAvatar();
  },
  methods: {
    createAvatar() {
      const canvas = document.querySelector('#myCanvas');
      const img = new Avatar(canvas);
    },
  },
};
</script>

<style lang="stylus" scoped>
.avatar-container {
  width: 100%;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;

  .button {
    margin-left: 30px;
    border: 1px solid #00ADB5;
    padding: 4px 6px;
    border-radius: 4px;
    cursor: pointer;
  }
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

# avatar.js

export default class Avatar {
  constructor(canvasDom) {
    Avatar.drawImage(canvasDom);
  }

  static createColor() {
    return `#${Math.floor(Math.random() * 0xFFFFFF).toString(16).padEnd(6, '0')}`;
  }

  static getDrawBolck() {
    // 从一百个格子中选出需要填充的 左右对称 10 * 5 的二维数组
    const block = new Array(10).fill(0).map((el) => new Array(5).fill(false));
    for (let i = 0; i < 10; i++) {
      // 一行左半边填充格子个数1-5
      let blockNum = Math.floor(Math.random() * 5) + 1;
      while (blockNum) {
        const index = Math.floor(Math.random() * 5); // 0-4
        if (!block[i][index]) {
          block[i][index] = true;
          blockNum--;
        }
      }
    }
    return block;
  }

  static drawImage(canvasDom) {
    if (canvasDom) {
      const canvas = canvasDom;
      const ctx = canvas.getContext('2d');
      Avatar.clear(ctx);
      ctx.fillStyle = Avatar.createColor();
      const drawBolck = Avatar.getDrawBolck();
      for (let i = 0; i < 10; i++) {
        for (let j = 0; j < 5; j++) {
          if (drawBolck[i][j]) {
            ctx.fillRect(10 * j, 10 * i, 10, 10);
            ctx.fillRect(10 * (9 - j), 10 * i, 10, 10);
          }
        }
      }
    }
  }

  static clear(ctx) {
    ctx.fillStyle = '#FFFFFF';
    ctx.fillRect(0, 0, 100, 100);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
最近更新: 2023年03月21日 14:47:21