11<template >
22 <div >
3- <img ref =" imageRef" :src =" props.src" :alt =" props.alt" :style =" [imageStyle, props.imgStyle]" />
3+ <img
4+ ref =" imageRef"
5+ :src =" props.src"
6+ :alt =" props.alt"
7+ :crossorigin =" imgCrossOrigin"
8+ :style =" [imageStyle, props.imgStyle]"
9+ />
410 </div >
511</template >
612
713<script setup lang="ts">
814import Cropper from ' cropperjs'
915import { nextTick , onMounted , ref , toRaw , watch } from ' vue'
10- import type { CSSProperties , PropType } from ' vue'
16+ import type { CSSProperties , PropType , ImgHTMLAttributes } from ' vue'
1117/* Ensure the size of the image fit the container perfectly */
1218const imageStyle = {
1319 display: ' block' ,
@@ -28,6 +34,10 @@ const props = defineProps({
2834 type: Object as PropType <CSSProperties >,
2935 default : () => ({})
3036 },
37+ imgCrossOrigin: {
38+ type: String as PropType <ImgHTMLAttributes [' crossorigin' ]>,
39+ default: undefined
40+ },
3141 // ========= CropperJS options =======
3242 // Define the view mode of the cropper
3343 viewMode: {
@@ -218,21 +228,24 @@ const props = defineProps({
218228
219229const imageRef = ref ()
220230
221- let cropper: Cropper
222-
231+ let cropper: Cropper | undefined
223232function initCropper() {
224- return new Cropper (imageRef .value , toRaw (props ) as unknown as Cropper .Options )
233+ if (props .src ) {
234+ cropper = new Cropper (imageRef .value , toRaw (props ) as unknown as Cropper .Options )
235+ } else {
236+ cropper = undefined
237+ }
225238}
226239
227240// init when first mounted
228- onMounted (() => ( cropper = initCropper ()) )
241+ onMounted (initCropper )
229242
230243// reinit when props change
231244watch (
232245 () => props ,
233246 () => {
234- cropper .destroy ()
235- nextTick (() => ( cropper = initCropper ()) )
247+ cropper ? .destroy ()
248+ nextTick (initCropper )
236249 },
237250 { deep: true }
238251)
@@ -440,15 +453,19 @@ defineExpose({
440453 * flip the image horizontally
441454 */
442455 flipX() {
443- const { scaleX } = cropper .getData ()
444- cropper .scaleX (- scaleX )
456+ if (cropper ) {
457+ const { scaleX } = cropper .getData ()
458+ cropper .scaleX (- scaleX )
459+ }
445460 },
446461 /**
447462 * flip the image vertically
448463 */
449464 flipY() {
450- const { scaleY } = cropper .getData ()
451- cropper .scaleY (- scaleY )
465+ if (cropper ) {
466+ const { scaleY } = cropper .getData ()
467+ cropper .scaleY (- scaleY )
468+ }
452469 }
453470})
454471 </script >
0 commit comments