whychdw
2021-03-02 16c9e2760201ea5fd76581c6843af4f6c99ddbe2
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class CanvasImage {
    /**
     * 初始化类
     *
     * @param   {[object]}  el      canvas所在的容器
     * @param   {[object]}  option  配置项
     *
     * @return  {[object]}          canvasImage实例化对象
     */
    constructor(el, option) {
        this.el = el;
        this.option = option;
        this.cvs = "";
        this.ctx = "";
        this.width = 100;
        this.height = 100;
        
        // 初始化内容
        this.init(el, option);
    }
 
    init(el, option) {
        // 设置容器的宽高
        this.setWidth(option);
        this.setHeight(option);
 
        // 生成canvas容器和canvas
        this.createElement(el);
    }
 
    createElement(el) {
        // 生成容器
        const ctn = document.createElement('div');
        ctn.style.width = "100%";
        ctn.style.height = "100%";
        
        // 生成canvas
        const cvs = document.createElement('canvas');
        cvs.width = this.width;
        cvs.height = this.height;
        cvs.style.width = "100%";
        cvs.style.height = "100%";
        cvs.style.objectFit = "contain";
 
        this.cvs = cvs;
        this.ctx = cvs.getContext('2d');
        
        // 添加canvas
        ctn.appendChild(cvs);
        
        // 添加容器
        el.appendChild(ctn);
    }
 
    /**
     * 设置canvas的宽度
     *
     * @param   {[type]}  option  配置项
     *
     * @return  {[type]}          无
     */
    setWidth(option) {
        if(typeof option == 'object' && typeof option.width != 'undefined') {
            this.width = option.width;
        }else {
            this.width = 100;
        }
    }
 
    /**
     * 设置canvas的高度
     *
     * @param   {[type]}  option  配置项
     *
     * @return  {[type]}          无
     */
    setHeight(option) {
        if(typeof option == 'object' && typeof option.height != 'undefined') {
            this.height = option.height;
        }else {
            this.height = 100;
        }
    }
 
}
 
export default CanvasImage;