[cropperjs] Excellent and elegant front-end image cropping library

cropperjs download

npm i cropperjs

npm official website - https://www.npmjs.com/package/cropperjs


cropperjs key parameters

  • aspectRatio image cropping ratio
    • Default: NaN
    • Function: image cropping ratio
    • Value: custom crop ratio, such as 1 / 1, 4 / 3 , 16 / 9etc.

  • viewMode clipping mode
    • Default: 0
    • value:
      • 0: unlimited
      • 1: Limit the cropping frame to not exceed the size of the canvas.
      • 2: Limit the minimum size of the canvas to fit the container. If the canvas and container have different scales, the smallest canvas will be surrounded by extra space in one of the dimensions.
      • 3: Limit the minimum size of the canvas to fill the container. If the canvas and container have different scales, the container won't be able to fit the entire canvas in one of its dimensions.
      • Defines the view mode of the clipper. If viewMode is set to 0, the crop box can extend beyond the canvas, while a value of 1, 2, or 3 will constrain the crop box to the size of the canvas. A viewMode of 2 or 3 will additionally constrain the canvas to the container. There is no difference between 2 and 3 when the canvas and container have the same ratio.

  • dragMode The drag mode of the clipper
    • Default: crop
    • value
      • crop: Create a new crop frame and delete the outside of the cropped area
      • move: move the canvas, while cropping, you can drag the picture
      • none: do nothing, no images can be dragged

Common methods of cropperjs

  • ready([ev])
    • Type: function
    • Function: execute this method after cropperjs is loaded
    • Used as a scene: when cropperjs is loaded, image data can be obtained in this method. Example: The loading of cropperjs is complete, and the image data of the first cropping is obtained

  • cropend(callback([ev]))
    • Type: function
    • Function: mouse/finger lift event, when the picture is cropped. You can operate on the image in this event function, such as converting the image to png, jpg, etc.

  • getCroppedCanvas()
    • Function: Get the cropped cnavas image data
  • Type: function
  • example↓
cropper.getCroppedCanvas()

  • setAspectRatio(rt)
    • Type: function
    • Function: Set the cropping ratio of the cropperjs instance
    • parameter:
      • rt: cropping ratio
        • Type: Number
    • example:cropper.setAspectRatio(16 / 9)

  • replace(url, [hasSameSize])
    • Function: set the newly cropped picture url
    • Type: function
    • parameter:
      • url: replace the url of the image
      • hasSameSize: If the new image is the same size as the old one, then it will not rebuild the cropper, but just update the URLs of all related images. This can be used to apply filters.
    • example:cropperjs.replace('/public/123.png')

Package cropperjs component in vue

  • The role of monitoring props
    • Change the parent parameters to change the cropper settings in real time

src/components/cropperjs.vue

<template>
    <img ref="image" class="img" :src="props.url">
</template>

<script setup>
// 引入cropperjs库与相关css
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.min.css'

// 传来的图片地址
const props = defineProps({
      
      
    url: '',
    // 比例
    aspectRatio: {
      
      
        default: 1 / 1,
    }
}),
    image = ref(null),//img元素 
    emit = defineEmits(['clip-img'])


// 监听props
watch(props, val => {
      
      
    // 设置cropper
    cropper.setAspectRatio(val.aspectRatio)
    cropper.replace(val.url)
})

/**
 * 获取裁剪的base64图片发给父级
 * @param {canvas} cvs canvas数据
 */
const clipImgEmitBase64Img = cvs => {
      
      
    // 将canvas转为图片数据 → 参数1:图片格式[image/webp, image/jpeg, image/png] | 参数2:图片裁剪后的清晰度,相当于压缩图片 0 - 1(只对jpeg与webp有效)                 
    const base64 = cvs.toDataURL('image/webp', .75), 

    // 裁剪后发送数据给父级 
    emit('clip-img', base64)
}

let cropper = null
onMounted(() => {
      
      
    cropper = new Cropper(image.value, {
      
      
        aspectRatio: props.aspectRatio,//裁剪比例 → [1 / 1, 19 / 9 ,...........] 
        viewMode: 1,//裁剪模式 [0,1,2,3]
        dragMode: 'move',
        // 重点:加载完成将第一次裁剪的图片数据发给父级
         ready() {
      
      
            clipImgEmitBase64Img (this.cropper.getCroppedCanvas())
        },
        cropend() {
      
      
         	clipImgEmitBase64Img (this.cropper.getCroppedCanvas())
        }
    })
})
</script>

<style scoped>
.img {
      
      
    width: 100%;
    height: 100%;
    object-fit: contain;
    display: block;
    max-width: 100%;
}
</style>

Simple use of cropperjs components

src/views>HomeView.vue

<template>
	<button @click="updateImgUrl">修改图片</button>
    <cropper :url="clipImgCfg.url" @clip-img="clipImg" />
      
</template>

<script setup>
import {
      
       reactive } from 'vue';
const clipImgCfg = reactive({
      
      
  url:'/public/111.jpg',
  rt:1 / 1
})

const updateImgCfg = ()=> {
      
      
  clipImgCfg.url='/public/99999.jpg' 
  clipImgCfg.rt=16 / 9 
}

// 裁剪后的图片事件
const clipImg = imgData => console.log(imgData)
</script>

renderings

insert image description here


base64 to file object File

  • When the image needs to be converted to a file object and uploaded to the server after cropping↓
    base64 to the file object File
  • Alternate address - http://t.csdn.cn/jQ1A5

Guess you like

Origin blog.csdn.net/qq_43614372/article/details/131055593