Skip to content

ImgCropper

Image cropping component for image cropping, supporting drag, zoom, rotate, and other operations.

Component Type

Basic Usage

The image cropping component needs to bind v-model to control the component's display and hide, and control the displayed image resource through the img-src property. After entering the component, you can drag, pinch-zoom, rotate, and other operations on the image. Listen to the confirm event to get the cropping result.

Note: It is recommended to use the image cropping component in a new page, keeping show as true, and return to the previous page after cropping is complete.

html
<wd-img-cropper
  v-model="show"
  :img-src="src"
  @confirm="handleConfirm"
  @cancel="handleCancel"
>
</wd-img-cropper>
<view class="profile">
  <view v-if="!imgSrc" class="img" @click="upload">
    <wd-icon name="fill-camera" custom-class="img-icon"></wd-icon>
  </view>
  <wd-img v-if="imgSrc" round width="200px" height="200px" :src="imgSrc" mode="aspectFit" custom-class="profile-img" @click="upload" />
  <view style="font-size: 14px;">Click to upload avatar</view>
</view>
typescript
const src = ref<string>('')
const imgSrc = ref<string>('')
const show = ref<boolean>(false)

function upload() {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const tempFilePaths = res.tempFilePaths[0]
      src.value = tempFilePaths
      show.value = true
    }
  })
}
function handleConfirm(event) {
  const { tempFilePath } = event
  imgSrc.value = tempFilePath
}
function imgLoaderror(res) {
  console.log('Loading failed', res)
}
function imgLoaded(res) {
  console.log('Loading successful', res)
}
function handleCancel(event) {
  console.log('Cancel', event)
}

Component Configuration

Custom Crop Ratio

Set the crop frame's aspect ratio through the aspect-ratio property, in the format width:height.

3:2 Suitable for Photography

html
<wd-img-cropper
  v-model="show"
  :img-src="src"
  aspect-ratio="3:2"
  @confirm="handleConfirm"
  @cancel="handleCancel"
>
</wd-img-cropper>

16:9 Film Ratio

html
<wd-img-cropper
  v-model="show"
  :img-src="src"
  aspect-ratio="16:9"
  @confirm="handleConfirm"
  @cancel="handleCancel"
>
</wd-img-cropper>

16:10 So Wide, Very Stylish

The 16:10 display ratio is very suitable for displaying landscape photos or movie posters and other widescreen content.

html
<wd-img-cropper
  v-model="show"
  :img-src="src"
  aspect-ratio="16:10"
  @confirm="handleConfirm"
  @cancel="handleCancel"
>
</wd-img-cropper>

Special Usage

Upload After Cropping

Combined with useUpload, you can achieve automatic image upload after cropping is complete.

html
<wd-img-cropper
  v-model="show"
  :img-src="src"
  @confirm="handleConfirmUpload"
  @cancel="handleCancel"
>
</wd-img-cropper>
typescript
import { ref } from 'vue'
import { useUpload, useToast } from '@/uni_modules/wot-ui'
import { type UploadFileItem } from '@/uni_modules/wot-ui/components/wd-upload/types'

const { startUpload, UPLOAD_STATUS } = useUpload()
const { show: showToast } = useToast()

const show = ref(false)
const src = ref('')
const imgSrc = ref('')

async function handleConfirmUpload(event) {
  const { tempFilePath } = event
  
  // Build upload file object
  const file: UploadFileItem = {
    url: tempFilePath,
    status: UPLOAD_STATUS.PENDING,
    percent: 0,
    uid: new Date().getTime()
  }

  try {
    // Start upload
    await startUpload(file, {
      action: 'https://your-upload-url',
      onSuccess() {
        imgSrc.value = tempFilePath
        showToast({
          msg: 'Upload successful'
        })
      },
      onError() {
        showToast({
          msg: 'Upload failed'
        })
      },
      onProgress(res) {
        console.log('Upload progress:', res.progress)
      }
    })
  } catch (error) {
    console.error('Upload failed:', error)
  }
}

Attributes

ParameterDescriptionTypeDefault Value
v-modelOpen image cropping componentbooleanfalse
img-srcImage resource linkstring-
img-widthInitial width of the screenshot preview image; 1. If width is set but height is not, scale proportionally according to width; 2. If neither is set, the preview image size will be scaled proportionally according to the crop frame size, with edge locking processing;; string type only supports % unit, number type unit is pxnumber | string-
img-heightInitial height of the screenshot preview image; 1. If height is set but width is not, scale proportionally according to height; 2. If neither is set, the preview image size will be scaled proportionally according to the crop frame size, with edge locking processing;; string type only supports % unit, number type unit is pxnumber | string-
disabled-rotateDisable image rotationbooleanfalse
export-scaleSet exported image sizenumber2
max-scaleMaximum zoom multiplenumber3
cancel-button-textCancel button textstringCancel
confirm-button-textConfirm button textstringDone
qualityGenerated image quality wx.canvasToTempFilePath property introductionnumber1
file-typeTarget file type, wx.canvasToTempFilePath property introductionstringpng
aspect-ratio v1.9.0Crop frame aspect ratio, format is width:heightstring1:1

Events

Event NameDescriptionParameters
confirmTriggered when screenshot is complete{tempFilePath, width, height} are the temporary path (local path) of the generated file, the width of the generated image, and the height of the generated image respectively
cancelTriggered when screenshot is cancelled-
imgloaderrorTriggered when image loading fails{err}
imgloadedTriggered when image loading is complete{res}

Methods

Expose internal component functions through ref:

Method NameDescriptionParametersReturn Value
setRotateSet image rotation angledeg (the rotation angle to be set)-
resetImgReset image angle, zoom, and position--
revertIsAnimationToggle image transition animation effectanimation (whether to enable animation)-

External Style Classes

Class NameDescription
custom-classRoot node style

主题定制

CSS 变量

组件提供了下列 CSS 变量,可用于自定义样式,使用方法请参考 ConfigProvider 全局配置

名称默认值描述
--wot-img-cropper-bg$base-black组件背景色
--wot-img-cropper-z-index1组件层级
--wot-img-cropper-wrapper-bg$opac-7_45包裹器蒙层背景色
--wot-img-cropper-overlay-bg$opac-10_85裁剪区遮罩背景色
--wot-img-cropper-overlay-bg-highlight$base-transparent裁剪区遮罩高亮背景色
--wot-img-cropper-overlay-transition-duration0.2s遮罩过渡时长
--wot-img-cropper-cut-z-index9裁剪框层级
--wot-img-cropper-cut-border-color$base-white裁剪框边框颜色
--wot-img-cropper-corner-size$stroke-blod角标粗细
--wot-img-cropper-corner-length$n-20角标长度
--wot-img-cropper-corner-color$base-white角标颜色
--wot-img-cropper-gridline-border-color$base-white网格线边框颜色
--wot-img-cropper-img-z-index2图片层级
--wot-img-cropper-canvas-bg$base-white画布背景色
--wot-img-cropper-canvas-z-index10画布层级
--wot-img-cropper-footer-z-index10底部操作栏层级
--wot-img-cropper-footer-padding$padding-extra-loose底部操作栏内边距
--wot-img-cropper-footer-btn-margin$spacing-extra-spacious底部按钮向上边距
--wot-img-cropper-cancel-color$base-white取消按钮文字颜色
--wot-img-cropper-cancel-font-size$typography-body-size-extra-large取消按钮字号
--wot-img-cropper-icon-size$n-36旋转图标大小
--wot-img-cropper-icon-color$base-white旋转图标颜色

Source Code

Documentation
Component

Released under the MIT License.

Released under the MIT License.