一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服務器之家 - 編程語言 - JavaScript - vue.js - vue實現裁切圖片同時實現放大、縮小、旋轉功能

vue實現裁切圖片同時實現放大、縮小、旋轉功能

2022-01-10 16:28L6zt vue.js

這篇文章主要介紹了vue實現裁切圖片同時實現放大、縮小、旋轉功能,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

本篇文章主要介紹了vue實現裁切圖片同時實現放大、縮小、旋轉功能,分享給大家,具體如下:

實現效果:

  1. 裁切指定區域內的圖片
  2. 旋轉圖片
  3. 放大圖片
  4. 輸出bolb 格式數據 提供給 formdata 對象

效果圖

vue實現裁切圖片同時實現放大、縮小、旋轉功能

vue實現裁切圖片同時實現放大、縮小、旋轉功能

vue實現裁切圖片同時實現放大、縮小、旋轉功能

vue實現裁切圖片同時實現放大、縮小、旋轉功能

vue實現裁切圖片同時實現放大、縮小、旋轉功能

vue實現裁切圖片同時實現放大、縮小、旋轉功能

vue實現裁切圖片同時實現放大、縮小、旋轉功能

大概原理:

利用h5 filereader 對象, 獲取 <input type="file"/> “上傳到瀏覽器的文件” ,文件形式 為base64形式, 把 base64 賦給canvas的上下文。

然后給canvas 元素上加入對(mousedown)監聽事件。 當用戶鼠標左鍵在canvas按下時:

  1. 掛載對 window 對象mousemove事件 ---> 獲取 鼠標移動x,y距離.從而操作 canvas里的圖像的位置移動。
  2. 掛載對 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

延伸 · 閱讀

精彩推薦
  • vue.js用vite搭建vue3應用的實現方法

    用vite搭建vue3應用的實現方法

    這篇文章主要介紹了用vite搭建vue3應用的實現方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下...

    Asiter7912022-01-22
  • vue.jsVue2.x 項目性能優化之代碼優化的實現

    Vue2.x 項目性能優化之代碼優化的實現

    這篇文章主要介紹了Vue2.x 項目性能優化之代碼優化的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋...

    優小U9632022-02-21
  • vue.jsVue中引入svg圖標的兩種方式

    Vue中引入svg圖標的兩種方式

    這篇文章主要給大家介紹了關于Vue中引入svg圖標的兩種方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的...

    十里不故夢10222021-12-31
  • vue.jsVue2.x-使用防抖以及節流的示例

    Vue2.x-使用防抖以及節流的示例

    這篇文章主要介紹了Vue2.x-使用防抖以及節流的示例,幫助大家更好的理解和學習使用vue框架,感興趣的朋友可以了解下...

    Kyara6372022-01-25
  • vue.js梳理一下vue中的生命周期

    梳理一下vue中的生命周期

    看過很多人講vue的生命周期,但總是被繞的云里霧里,尤其是自學的同學,可能js的基礎也不是太牢固,聽起來更是吃力,那我就已個人之淺見,以大白話...

    CRMEB技術團隊7992021-12-22
  • vue.js詳解vue 表單綁定與組件

    詳解vue 表單綁定與組件

    這篇文章主要介紹了vue 表單綁定與組件的相關資料,幫助大家更好的理解和學習使用vue框架,感興趣的朋友可以了解下...

    Latteitcjz6432022-02-12
  • vue.jsVue多選列表組件深入詳解

    Vue多選列表組件深入詳解

    這篇文章主要介紹了Vue多選列表組件深入詳解,這個是vue的基本組件,有需要的同學可以研究下...

    yukiwu6752022-01-25
  • vue.jsVue項目中實現帶參跳轉功能

    Vue項目中實現帶參跳轉功能

    最近做了一個手機端系統,其中遇到了父頁面需要攜帶參數跳轉至子頁面的問題,現已解決,下面分享一下實現過程,感興趣的朋友一起看看吧...

    YiluRen丶4302022-03-03
主站蜘蛛池模板: 午夜爱情动作片P | 久久se精品一区二区国产 | 精品国产理论在线观看不卡 | 久久视热频国产这里只有精品23 | 日本不卡视频免费的 | 成人伊人青草久久综合网破解版 | 清纯唯美 亚洲 | 拔插拔插8x8x海外华人免费视频 | 日本成人黄色片 | 五月天精品视频播放在线观看 | 无遮18禁在线永久免费观看挡 | 青青青青久久国产片免费精品 | 拔插拔插成人 | 胸大的姑娘中文字幕视频 | 亚洲欧美国产精品完整版 | 久久黄色精品视频 | 久久er99热精品一区二区 | 国产欧美va欧美va香蕉在线观 | 亚洲欧美一级夜夜爽w | 午夜亚洲WWW湿好大 午夜想想爱 | 图片专区小说专区卡通动漫 | 色天天综合网色鬼综合 | 99久久免费国产特黄 | 久久精品成人免费看 | 亚洲国产第一 | 国内自拍网红在线综合 | 色批网站www | 91午夜剧场| 久久免费黄色 | 亚洲国产精品二区久久 | 公交车高h | 香艳69xxxxx有声小说 | 天天综合色天天综合 | 亚洲高清国产拍精品动图 | 国产一卡2卡3卡四卡国色天香 | 插得爽 | 处女呦呦 | 91在线亚洲综合在线 | 欧美日韩国产在线一区 | 99精品热视频 | 大香人蕉免费视频75 |