gaoluyang
2026-06-24 712aa51536236d43e87273e4ce45ac5691dffad8
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
<script lang="ts" setup>
import type { CSSProperties } from 'vue';
 
import type { CropperProps } from './typing';
 
import { computed, onMounted, onUnmounted, ref, unref, useAttrs } from 'vue';
 
import { useDebounceFn } from '@vueuse/core';
import Cropper from 'cropperjs';
 
import { defaultOptions } from './typing';
 
import 'cropperjs/dist/cropper.css';
 
defineOptions({ name: 'CropperImage' });
 
const props = withDefaults(defineProps<CropperProps>(), {
  src: '',
  alt: '',
  circled: false,
  realTimePreview: true,
  height: '360px',
  crossorigin: undefined,
  imageStyle: () => ({}),
  options: () => ({}),
});
 
const emit = defineEmits(['cropend', 'ready', 'cropendError']);
const attrs = useAttrs();
 
type ElRef<T extends HTMLElement = HTMLDivElement> = null | T;
const imgElRef = ref<ElRef<HTMLImageElement>>();
const cropper = ref<Cropper | null>();
const isReady = ref(false);
 
const debounceRealTimeCropped = useDebounceFn(realTimeCropped, 80);
 
const getImageStyle = computed((): CSSProperties => {
  return {
    height: props.height,
    maxWidth: '100%',
    ...props.imageStyle,
  };
});
 
const getClass = computed(() => {
  return [
    attrs.class,
    {
      'cropper-image--circled': props.circled,
    },
  ];
});
 
const getWrapperStyle = computed((): CSSProperties => {
  return { height: `${`${props.height}`.replace(/px/, '')}px` };
});
 
onMounted(init);
 
onUnmounted(() => {
  cropper.value?.destroy();
});
 
async function init() {
  const imgEl = unref(imgElRef);
  if (!imgEl) {
    return;
  }
  cropper.value = new Cropper(imgEl, {
    ...defaultOptions,
    ready: () => {
      isReady.value = true;
      realTimeCropped();
      emit('ready', cropper.value);
    },
    crop() {
      debounceRealTimeCropped();
    },
    zoom() {
      debounceRealTimeCropped();
    },
    cropmove() {
      debounceRealTimeCropped();
    },
    ...props.options,
  });
}
 
// Real-time display preview
function realTimeCropped() {
  props.realTimePreview && cropped();
}
 
// event: return base64 and width and height information after cropping
function cropped() {
  if (!cropper.value) {
    return;
  }
  const imgInfo = cropper.value.getData();
  const canvas = props.circled
    ? getRoundedCanvas()
    : cropper.value.getCroppedCanvas();
  canvas.toBlob((blob) => {
    if (!blob) {
      return;
    }
    const fileReader: FileReader = new FileReader();
    fileReader.readAsDataURL(blob);
    fileReader.onloadend = (e) => {
      emit('cropend', {
        imgBase64: e.target?.result ?? '',
        imgInfo,
      });
    };
    fileReader.addEventListener('error', () => {
      emit('cropendError');
    });
  }, 'image/png');
}
 
// Get a circular picture canvas
function getRoundedCanvas() {
  const sourceCanvas = cropper.value!.getCroppedCanvas();
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d')!;
  const width = sourceCanvas.width;
  const height = sourceCanvas.height;
  canvas.width = width;
  canvas.height = height;
  context.imageSmoothingEnabled = true;
  context.drawImage(sourceCanvas, 0, 0, width, height);
  context.globalCompositeOperation = 'destination-in';
  context.beginPath();
  context.arc(
    width / 2,
    height / 2,
    Math.min(width, height) / 2,
    0,
    2 * Math.PI,
    true,
  );
  context.fill();
  return canvas;
}
 
function handleImageError() {
  emit('cropendError');
}
</script>
 
<template>
  <div :class="getClass" :style="getWrapperStyle">
    <img
      v-show="isReady"
      ref="imgElRef"
      :alt="alt"
      :crossorigin="crossorigin"
      :src="src"
      :style="getImageStyle"
      @error="handleImageError"
      class="h-auto max-w-full"
    />
  </div>
</template>
 
<style lang="scss">
.cropper-image {
  &--circled {
    .cropper-view-box,
    .cropper-face {
      border-radius: 50%;
    }
  }
}
</style>