fabric.js 翻转,复制粘贴,隐藏, 删除,历史记录,撤销, 剪切, 图层,组合打散,锁定等功能

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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
用vue写的
 
显示,隐藏
hide(){
        this.canvas.getActiveObject().set('opacity', 0).setCoords();
        this.canvas.requestRenderAll()
    },
    display(){
        this.canvas.getActiveObject().set('opacity', 1).setCoords();
        this.canvas.requestRenderAll()
    },
 
翻转 水平    垂直用scaleY
flip(){
        this.canvas.getActiveObject().set('scaleX', -1).setCoords();
        this.canvas.requestRenderAll();
    },
 
克隆(复制粘贴)
 
paste(_clipboard){
        // clone again, so you can do multiple copies.
        let canvas = this.canvas;
        _clipboard.clone(function(clonedObj) {
            canvas.discardActiveObject();
            clonedObj.set({
                left: clonedObj.left + 20,
                top: clonedObj.top + 20,
                evented: true,
            });
            if (clonedObj.type === 'activeSelection') {
                // active selection needs a reference to the canvas.
                clonedObj.canvas = canvas;
                clonedObj.forEachObject(function(obj) {
                    canvas.add(obj);
                });
                // this should solve the unselectability
                clonedObj.setCoords();
            } else {
                canvas.add(clonedObj);
            }
            _clipboard.top += 20;
            _clipboard.left += 20;
            canvas.setActiveObject(clonedObj);
            // canvas.requestRenderAll();
        });
    },
    copy(){
       let canvas = this.canvas;
       var _self = this;
        canvas.getActiveObject().clone(function(cloned){
            // let _clipboard = cloned;
              _self.paste(cloned);
             
        })
    },   
 
历史记录,回退撤销
 
data 初始化
config : {
            canvasState             : [],
            currentStateIndex       : -1,
            redoStatus              : false, //撤销状态
            undoStatus              : false,  // 重做状态
            undoFinishedStatus      : 1,
            redoFinishedStatus      : 1,
            undoButton              : this.$refs.undo,  //得不到  在 mounted 得到
            redoButton              : this.$refs.redo,
        }
 
记录事件
canvasDataChange(){
      let _self = this;
      this.canvas.on('object:modified', function(){
          _self.updateCanvasState();
      });
      this.canvas.on('object:added', function(){
          _self.updateCanvasState()
      });
      this.canvas.on('object:removed', function(){
          _self.updateCanvasState()
      });
      this.canvas.on('object:rotating', function(){
          _self.updateCanvasState()
      });
    },
 
 
 undo() {
        let _self =this;
        if(this.config.undoFinishedStatus){
            if(this.config.currentStateIndex == -1){
                this.config.undoStatus = false;
            }
            else{
                if (this.config.canvasState.length >= 1) {
                    this.config.undoFinishedStatus = 0;
                    if(this.config.currentStateIndex != 0){
                        this.config.undoStatus = true;
                        this.canvas.loadFromJSON(this.config.canvasState[this.config.currentStateIndex-1],function(){
                                var jsonData = JSON.parse(_self.config.canvasState[_self.config.currentStateIndex-1]);
                                _self.canvas.renderAll();
                                _self.config.undoStatus = false;
                                _self.config.currentStateIndex -= 1;
                                    // _self.config.undoButton.removeAttribute("disabled");
                                    // _self.config.undoButton.disabled = false;
                                    if(_self.config.currentStateIndex !== _self.config.canvasState.length-1){
                                        // _self.config.redoButton.removeAttribute('disabled');
                                        // _self.config.redoButton.disabled = false;
                                    }
                                _self.config.undoFinishedStatus = 1;
                        });
                    }
                    else if(_self.config.currentStateIndex == 0){
                        _self.canvas.clear();
                        _self.config.undoFinishedStatus = 1;
                        // _self.config.undoButton.disabled= "disabled";
                        // _self.config.redoButton.removeAttribute('disabled');
                        // _self.config.redoButton.disabled = false;
                        _self.config.currentStateIndex -= 1;
                    }
                }
            }
        }
    },
    redo() {
        let _self = this;
        if(this.config.redoFinishedStatus){
            if((this.config.currentStateIndex == this.config.canvasState.length-1) && this.config.currentStateIndex != -1){
                // this.config.redoButton.disabled= true;
            }else{
            if(this.config.canvasState.length > this.config.currentStateIndex && this.config.canvasState.length != 0){
                this.config.redoFinishedStatus = 0;
                this.config.redoStatus = true;
                this.canvas.loadFromJSON(this.config.canvasState[this.config.currentStateIndex+1],function(){
                    var jsonData = JSON.parse(_self.config.canvasState[_self.config.currentStateIndex+1]);
                    _self.canvas.renderAll();
                    _self.config.redoStatus = false;
                    _self.config.currentStateIndex += 1;
                    if(_self.config.currentStateIndex != -1){
                    //    _self.config.redoButton.disabled = false;
                    }
                    _self.config.redoFinishedStatus = 1;
                    if((_self.config.currentStateIndex == _self.config.canvasState.length-1) && _self.config.currentStateIndex != -1){
                        // _self.config.redoButton.disabled= true;
                    }
              });
            }
            }
        }
    },
 
删除
del() {
      var el = this.canvas.getActiveObject();
      this.canvas.remove(el);
    },
 
格式化 数据
toJson(){
    
      console.log(JSON.stringify(this.canvas.toJSON()));
    },
    toSVG(){
      // return this.canvas.toSVG()
      console.log(this.canvas.toSVG());
    },
 
 
canvas导出为图片并下载
 
canvasToImage(){
      var MIME_TYPE = "image/png";
      //转换成base64
      var imgURL = this.canvas.toDataURL(MIME_TYPE);
    //创建一个a链接,模拟点击下载
    var dlLink = document.createElement('a');
      var filename = '个人画板_' + (new Date()).getTime() + '.png';
    dlLink.download = filename;
    dlLink.href = imgURL;
    dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');
    document.body.appendChild(dlLink);
    dlLink.click();
    document.body.removeChild(dlLink); 
    },
 
或者
downloadimage(event){
      // 图片导出为 png 格式
      var type = 'png';
      // 返回一个包含JPG图片的<img>元素
      var img_png_src = this.canvas.toDataURL("image/png");  //将画板保存为图片格式的函数
      var imgData = img_png_src.replace(this._fixType(type),'image/octet-stream');
      
      var filename = '个人画板_' + (new Date()).getTime() + '.' + type;
 
      this.saveFile(imgData,filename);
    },
 
    saveFile(data, filename){
      var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
      save_link.href = data;
      save_link.download = filename;
      var event = document.createEvent('MouseEvents');
      event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      save_link.dispatchEvent(event);
    },
 
    _fixType(type) {
      type = type.toLowerCase().replace(/jpg/i, 'jpeg');
      var r = type.match(/png|jpeg|bmp|gif/)[0];
      return 'image/' + r;
    },
 
 
组合 打散
group() {
      this.fabricAction.fabricObjGroup(this);
    },
    ungroup() {
      this.fabricAction.fabricObjUnGroup(this);
    },
 
锁定
lock() {
      this.fabricAction.lockOption(this);
    },

  

posted @   高中国流  阅读(10192)  评论(6编辑  收藏  举报
编辑推荐:
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
阅读排行:
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 《HelloGitHub》第 106 期
· 数据库服务器 SQL Server 版本升级公告
· 深入理解Mybatis分库分表执行原理
· 使用 Dify + LLM 构建精确任务处理应用
点击右上角即可分享
微信分享提示