Based on Vue2 the functions of uploading compressing dragging and sorting dragging and deleting pictures on mobile terminal are realized

  • 2021-10-16 01:01:37
  • OfStack

Directory picture upload picture compression drag-and-drop sort, drag-and-drop delete

Use Vue2 to realize the functions of uploading, compressing, dragging and sorting, dragging and deleting pictures on the mobile terminal. Picture uploading, compressing, dragging and sorting, dragging and deleting
The mobile H5 page, which has been developed in the company for a period of time before, has a function of uploading pictures + compressing. Refer to the method of 1 under the net, plus the process of my own exploration, and finally realize this function. Later, when you are idle at home, you add a long press to select pictures, and you can drag and sort them, and drag and drop them to the specified position to delete them.

github Address: Code Address

Let's get down to business:

Picture upload

The picture upload is realized by HTML's input tag. The core is to convert the obtained files into pictures through FileReader, and the code is as follows:


<input type="file" accept="image/*" capture="camera" @change="selectFile">

selectFile(event:any){
 	this.showAlert = false  
 	if (event.target.files && event.target.files.length > 0) {
   this.isLoading = true
   let file:any = event.target.files[0]
   let fr:any = new FileReader()
   fr.readAsDataURL(file)
   fr.onload = (imgObj:any) => {
    let img:any = new Image()
    img.src = imgObj.target.result
    img.onload = (e:any) => {
     //  You can get the uploaded pictures here 
     })
    }
   }
  }
}

Picture compression

Image compression is achieved by canvas redrawing method, and the specific code is as follows:


//  Omit the above code 
fr.onload = (imgObj:any) => {
	//  After getting the picture file, 
 let img:any = new Image()
 img.src = imgObj.target.result
 img.onload = (e:any) => {
  Compress(img,e.path[0].height,e.path[0].width,(newImg:any) => {
   this.imgList.push(newImg)
   this.isLoading = false
   //  Drag and drop function to be added 
  })
 }
}

/**
 *  Picture compression 
 * @param img  Picture object 
 */
export function Compress(img:any,height:number,width:number,callback:Function) {
 let canvas:any = document.createElement('canvas')
 let context:any = canvas.getContext('2d')
 canvas.width = width
 canvas.height = height
 context.clearRect(0,0,width,height)
 context.drawImage(img,0,0,width,height)
 callback(canvas.toDataURL("image/jpeg", 0.75))
}

Drag and drop sort, drag and drop delete

Drag-and-drop sort, drag-and-drop deletion to a specified location is accomplished by listening for touch events.
Core ideas:
1. Obtain the picture dom element, and add ontouchstart, ontouchend and ontouchmove methods to the picture dom element.
2. In the ontouchstart method, there are new1 time nodes and new1 time nodes in ontouchend, and the time interval between the two time nodes is judged to be a click event or a long press event.
3. In ontouchstart, setting settimeout method is to delay judging whether it is a click method or a long-press method. If it is a long-press method, the position in the page where the picture is located is obtained, the position of the picture is set to the position of the click screen, and the layout mode of the picture is changed. In ontouchmove method, the position of the picture is set to follow the position change of the touch screen.
4. When the hand is released after moving the picture, the ontouchend method is triggered to judge whether the position of the picture is in the deleted area after the finger leaves. If so, the picture is deleted, the picture list is rendered again, and the touch method is added again.
If it is not in the deleted area, sort the picture position and restore the picture style after sorting. And force the picture list to be rendered again.

The code is as follows:


Compress(img,e.path[0].height,e.path[0].width,(newImg:any) => {
 this.imgList.push(newImg)
 this.isLoading = false
 //  Give the addition method here 
 setTimeout(() => {
  this.addTouchEvent() 
 });
})



addTouchEvent(){
 let domList:any = document.querySelectorAll('.show-img')
 if (domList) {
  let domMoveFlag:boolean = true
  domList.forEach((item:any,index:any) => {
   item.ontouchstart = null
   item.ontouchmove = null
   item.ontouchend = null
   item.ontouchstart = (startEvent:any) => {
    startEvent.preventDefault()
    console.log(startEvent)
    this.touchStartTime = new Date()
    setTimeout(() => { 
     if (domMoveFlag) {  
      console.log(' Perform the element position operation procedure ')
      this.showDeleteArea = true
      let domClient:any = item.getBoundingClientRect()
      console.log(domClient)
      this.firstPosition = {
       x:startEvent.changedTouches[0].pageX,
       y:startEvent.changedTouches[0].pageY
      }
      item.style.position = 'fixed'
      item.style.height = domClient.height + 'px'
      item.style.width = domClient.width + 'px'
      item.style.top = domClient.top + 'px'
      item.style.left = domClient.left + 'px'
      item.style.padding = 0
      item.style.zIndex = 9
      //  Add a drag event 
      item.ontouchmove = (moveEvent:any) => {
       // console.log(moveEvent)
       item.style.top = moveEvent.changedTouches[0].pageY - this.firstPosition.y + domClient.top + 'px'
       item.style.left = moveEvent.changedTouches[0].pageX - this.firstPosition.x + domClient.left + 'px'
      }      
     }   
    }, 600);
   }
   item.ontouchend = (endEvent:any) => {
    let time:any = new Date()
    console.log(time - this.touchStartTime)
    if (time - this.touchStartTime <= 400) {
     domMoveFlag = false
     item.click()
     setTimeout(() => {
      this.addTouchEvent() 
     });
    } else {
     let newItemCenter:any = item.getBoundingClientRect()
     let centerY:any = newItemCenter.top + newItemCenter.height / 2
     let centerX:any = newItemCenter.left + newItemCenter.width / 2
     let deleteDom:any = document.querySelector(".deleteImg")
     let deleteArea:any = deleteDom.getBoundingClientRect()
     if (centerY >= deleteArea.top) {
      let _imgList = JSON.parse(JSON.stringify(this.imgList))
      let currentImg:any = _imgList.splice(index,1)
      this.imgList = []
      this.showDeleteArea = false
      setTimeout(() => {
       this.imgList = _imgList
       setTimeout(() => {
        this.addTouchEvent() 
       });
      });
      return
     }
     this.showDeleteArea = false
     //  Calculate the page position of all picture elements 
     let domParentList:any = document.querySelectorAll('.imgCtn')
     domParentList && domParentList.forEach((domParent:any,cindex:any) => {
      let domPos:any = (domParent.getBoundingClientRect())
      if ( 
       centerY >= domPos.top 
       && centerY <= domPos.bottom 
       && centerX >= domPos.left
       && centerX <= domPos.right
      ) {
       //  Reordering 
       console.log(' Within the target area, reorder ')
       let _imgList = JSON.parse(JSON.stringify(this.imgList))
       let currentImg:any = _imgList.splice(index,1)
       _imgList.splice(cindex,0,...currentImg)
       this.imgList = []
       setTimeout(() => {
        this.imgList = _imgList
        setTimeout(() => {
         this.addTouchEvent() 
        });
       });
      }
     });
     //  Restore style 
     item.style.position = 'absolute';
     item.style.height = '100%'
     item.style.width = '100%'
     item.style.top = '0'
     item.style.left = '0'
     item.style.padding = '10px'
    }
   }
  })
 }
}

At this point, the uploading, compression, drag-and-drop sorting and drag-and-drop deletion functions of pictures have been completed.


Related articles: