本篇文章主要介紹了vue實現裁切圖片同時實現放大、縮小、旋轉功能,分享給大家,具體如下:
實現效果:
- 裁切指定區域內的圖片
- 旋轉圖片
- 放大圖片
- 輸出bolb 格式數據 提供給 formdata 對象
效果圖
大概原理:
利用h5 filereader 對象, 獲取 <input type="file"/> “上傳到瀏覽器的文件” ,文件形式 為base64形式, 把 base64 賦給canvas的上下文。
然后給canvas 元素上加入對(mousedown)監聽事件。 當用戶鼠標左鍵在canvas按下時:
- 掛載對 window 對象mousemove事件 ---> 獲取 鼠標移動x,y距離.從而操作 canvas里的圖像的位置移動。
- 掛載對 window 對象mouseup 事件, 清除 mousemove事件的綁定。(同時該事件觸發后會被刪除)
剩下的 放大、縮小 、 旋轉 是對 canvas 對象的操作/坐標體系的操作。具體api詳見mdn canvas 文檔
代碼
dom.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
|
export const on = ({el, type, fn}) => { if ( typeof window) { if (window.addeventlistener) { el.addeventlistener(type, fn, false ) } else { el.attachevent(`on${type}`, fn) } } } export const off = ({el, type, fn}) => { if ( typeof window) { if (window.addeventlistener) { el.removeeventlistener(type, fn) } else { el.detachevent(`on${type}`, fn) } } } export const once = ({el, type, fn}) => { const hyfn = (event) => { try { fn(event) } finally { off({el, type, fn: hyfn}) } } on({el, type, fn: hyfn}) } // 最后一個 export const fbtwice = ({fn, time = 300}) => { let [ctime, k] = [ null , null ] // 獲取當前時間 const gettime = () => new date().gettime() // 混合函數 const hyfn = () => { const ags = argments return () => { cleartimeout(k) k = ctime = null fn(...ags) } } return () => { if (ctime == null ) { k = settimeout(hyfn(...arguments), time) ctime = gettime() } else { if ( gettime() - ctime < 0) { // 清除之前的函數堆 ---- 重新記錄 cleartimeout(k) k = null ctime = gettime() k = settimeout(hyfn(...arguments), time) } }} } export const contains = function (parentnode, childnode) { if (parentnode.contains) { return parentnode != childnode && parentnode.contains(childnode) } else { return !!(parentnode.comparedocumentposition(childnode) & 16) } } export const addclass = function (el, classname) { if ( typeof el !== "object" ) { console.log( 'el is not elem' ) return null } let classlist = el[ 'classname' ] classlist = classlist === '' ? [] : classlist.split(/\s+/) if (classlist.indexof(classname) === -1) { classlist.push(classname) el.classname = classlist.join( ' ' ) } else { console.warn( 'warn classname current' ) } } export const removeclass = function (el, classname) { let classlist = el[ 'classname' ] classlist = classlist === '' ? [] : classlist.split(/\s+/) classlist = classlist.filter(item => { return item !== classname }) el.classname = classlist.join( ' ' ) } export const delay = ({fn, time}) => { let ot = null let k = null return () => { // 當前時間 let ct = new date().gettime() const fixfn = () => { k = ot = null fn() } if (k === null ) { ot = ct k = settimeout(fixfn, time) return } if (ct - ot < time) { ot = ct cleartimeout(k) k = settimeout(fixfn, time) } } } export const event = function () { // 類型 this .typelist = {} } event.prototype.on = function ({type, fn}){ if ( this .typelist.hasownproperty(type)) { this .typelist[type].push(fn) } else { this .typelist[type] = [] this .typelist[type].push(fn) } } event.prototype.off = function ({type, fn}) { if ( this .typelist.hasownproperty(type)) { let list = this .typelist[type] let index = list.indexof(fn) if (index !== -1 ) { list.splice(index, 1) } } else { console.warn( 'not has this type' ) } } event.prototype.once = function ({type, fn}) { const fixfn = () => { fn() this .off({type, fn: fixfn}) } this .on({type, fn: fixfn}) } event.prototype.trigger = function (type){ if ( this .typelist.hasownproperty(type)) { this .typelist[type].foreach(fn => { fn() }) } } |
組件模板
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
|
< template > < div class = "jc-clip-image" :style = "{width: `${clip.width}`}" > < canvas ref = "ctx" :width = "clip.width" :height = "clip.height" @ mousedown = "handleclip($event)" > </ canvas > < input type = "file" ref = "file" @ change = "readfilemsg($event)" > < div class = "clip-scale-btn" > < a class = "add" @ click = "handlescale(false)" >+</ a > < a @ click = "rotate" class = "right-rotate" >轉</ a > < a class = "poor" @ click = "handlescale(true)" >-</ a > < span >{{scale}}</ span > </ div > < div class = "upload-warp" > < a class = "upload-btn" @ click = "dispatchupload($event)" >upload</ a > < a class = "upload-cancel" >cancel</ a > </ div > < div class = "create-canvas" > < a class = "to-send-file" @ click = "outfile" title = "請打開控制臺" >生成文件</ a > </ div > </ div > </ template > < script > import {on, off, once} from '../../utils/dom' export default { ctx: null, file: null, x: 0, // 點擊canvas x 鼠標地址 y: 0,// 點擊canvas y 鼠標地址 xv: 0, // 鼠標移動 x距離 yv: 0, // 鼠標移動 y距離 nx: 0, // 原始坐標點 圖像 x ny: 0,// 原始坐標點 圖像 y img: null, props: { src: { type: string, default: null }, clip: { type: object, default () { return {width: '200px', height: '200px'} } } }, data () { return { isshow: false, base64: null, scale: 1.5, //放大比例 deg: 0 //旋轉角度 } }, computed: { width () { const {clip} = this return parsefloat(clip.width.replace('px', '')) }, height () { const {clip} = this return parsefloat(clip.height.replace('px', '')) } }, mounted () { const {$options, $refs, width, height} = this // 初始化 canvas file nx ny object.assign($options, { ctx: $refs.ctx.getcontext('2d'), file: $refs.file, nx: -width / 2, ny: -height / 2 }) }, methods: { // 旋轉操作 rotate () { const {$options, draw} = this this.deg = (this.deg + math.pi /2)% (math.pi * 2) draw($options.img, $options.nx + $options.xv, $options.ny + $options.yv, this.scale, this.deg) }, // 處理放大 handlescale (flag) { const {$options, draw, deg} = this flag && this.scale > 0.1 && (this.scale = this.scale - 0.1) !flag && this.scale < 1.9 && ( this.scale = this.scale + 0.1) $options.img && draw($options.img, $options.nx + $options.xv, $options.ny + $options.yv, this.scale, deg) }, // 模擬file 點擊事件 dispatchupload (e) { this.clearstate() const {file} = this.$options e.preventdefault() file.click() }, // 讀取 input file 信息 readfilemsg () { const {file} = this.$options const {draw, createimage, $options: {nx, ny}, scale, deg} = this const wfile = file.files[0] const reader = new filereader() reader.onload = (e) => { const img = createimage(e.target.result, (img) => { draw(img, nx, ny, scale, deg) }) file.value = null } reader.readasdataurl(wfile) }, // 生成 圖像 createimage (src, cb) { const img = new image() this.$el.append(img) img.classname = 'base64-hidden' img.onload = () => { cb(img) } img.src = src this.$options.img = img }, // 操作畫布畫圖 draw (img, x = 0, y = 0, scale = 0.5,deg = math.pi ) { const {ctx} = this.$options let {width, height} = this // 圖片尺寸 let imgw = img.offsetwidth let imgh = img.offsetheight ctx.save() ctx.clearrect( 0, 0, width, height) ctx.translate( width / 2, height / 2, img) ctx.rotate(deg) ctx.drawimage(img, x, y, imgw * scale, imgh * scale) ctx.restore() }, // ... 事件綁定 handleclip (e) { const {handlemove, $options, deg} = this if (!$options.img) { return } object.assign(this.$options, { x: e.screenx, y: e.screeny }) on({ el: window, type: 'mousemove', fn: handlemove }) once({ el: window, type: 'mouseup', fn: (e) =>{ console.log('down') switch (deg) { case 0: { object.assign($options, { nx: $options.nx + $options.xv, ny: $options.ny + $options.yv, xv: 0, yv: 0 }) break; } case math.pi / 2: { object.assign($options, { nx: $options.ny + $options.yv, ny: $options.nx - $options.xv, xv: 0, yv: 0 }) break; } case math.pi: { object.assign($options, { nx: $options.nx - $options.xv, ny: $options.ny - $options.yv, xv: 0, yv: 0 }) break; } default: { // $options.ny - $options.yv, $options.nx + $options.xv object.assign($options, { nx: $options.ny - $options.yv, ny: $options.nx + $options.xv, xv: 0, yv: 0 }) } } off({ el: window, type: 'mousemove', fn: handlemove }) } }) }, // ... 處理鼠標移動 handlemove (e){ e.preventdefault() e.stoppropagation() const {$options, draw, scale, deg} = this object.assign($options, { xv: e.screenx - $options.x, yv: e.screeny - $options.y }) switch (deg) { case 0: { draw($options.img, $options.nx + $options.xv, $options.ny + $options.yv, scale, deg) break; } case math.pi / 2: { draw($options.img, $options.ny + $options.yv, $options.nx - $options.xv, scale, deg) break; } case math.pi: { draw($options.img, $options.nx - $options.xv, $options.ny - $options.yv, scale, deg) break; } default: { draw($options.img, $options.ny - $options.yv, $options.nx + $options.xv, scale, deg) break; } } }, // 清除狀態 clearstate () { const {$options, width, height} = this if ($options.img) { this.$el.removechild($options.img) object.assign($options, { x: 0, y: 0, xv: 0, yv: 0, nx: -width / 2, ny: -height / 2, img: null, }) } }, // 輸出文件 outfile () { const {$refs: {ctx}} = this console.log(ctx.todataurl()) ctx.toblob((blob) => {console.log(blob)}) } } } </ script > < style > @component-namespace jc { @component clip-image{ position: relative; width: 100%; canvas { position: relative; width: 100%; height: 100%; cursor: pointer; box-shadow: 0 0 3px #333; } input { display: none; } .base64-hidden { position: absolute; top: 0; left: 0; display: block; width: 100%; height: auto; z-index: -999; opacity: 0; } .clip-scale-btn { position: relative; @utils-clearfix; margin-bottom: 5px; text-align: center; a { float: left; width: 20px; height: 20px; border-radius: 50%; color: #fff; background: #49a9ee; text-align: center; cursor: pointer; } &>.poor, &>.right-rotate { float: right; } &>span{ position: absolute; z-index: -9; top: 0; left: 0; display: block; position: relative; width: 100%; text-align: center; height: 20px; line-height: 20px; } } .upload-warp { @utils-clearfix; .upload-btn,.upload-cancel { float: left; display:inline-block; width: 60px; height: 25px; line-height: 25px; color: #fff; border-radius: 5px; background: #49a9ee; box-shadow: 0 0 0 #333; text-align: center; top: 0; left: 0; right: 0; bottom: 0; margin: auto; cursor: pointer; margin-top: 5px; } .upload-cancel{ background: gray; float: right; } } .to-send-file { margin-top: 5px; display: block; width: 50px; height: 25px; line-height: 25px; color: #fff; border-radius: 5px; background: #49a9ee; cursor: pointer; } } |
項目代碼:https://github.com/l6zt/vuesrr
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://segmentfault.com/a/1190000013473331