vue-advanced-cropper 裁剪组件的使用:
// 其中需要的样式,我做了全局导入,当然直接在当前不额页面直接 import 'vue-advanced-cropper/dist/style.css'; 也是可以的
// 这两个组件 CircleStencil, RectangleStencil 主要用来设置 stencil-component 的,主要设置矩形裁剪还是圆形裁剪,默认是 RectangleStencil
// :stencil-props 用于设置在不同裁剪类型下的属性,分别参考
// https://advanced-cropper.github.io/vue-advanced-cropper/components/rectangle-stencil.html#props 和 https://advanced-cropper.github.io/vue-advanced-cropper/components/circle-stencil.html#props
// 还可以通过 backgroundClass 设置背景样式类
<script setup lang="ts">
import {
MModal,
MButton
} from "@mdpi-ui/design-system";
import {Cropper, CircleStencil, RectangleStencil} from 'vue-advanced-cropper';
interface Props {
src: string,
isCropperVisible: boolean
}
withDefaults(defineProps<Props>(), {
src: "",
isCropperVisible: false
})
const emit = defineEmits<{
cancel: void,
save: string
}>()
const cropper = ref<Cropper | null>(null)
const hint = ref("")
const cancel = () => {
hint.value = ""
emit('cancel')
}
const saveCropper = () => {
hint.value = ""
const { canvas } = cropper.value.getResult();
if (canvas) {
const form = new FormData();
const timestamp = new Date().getTime();
const filename = `${timestamp}.png`;
canvas.toBlob(async blob => {
form.append('file', blob, filename);
let img = new Image();
img.src = URL.createObjectURL(blob)
img.onload = function () {
let width = img.width
let height = img.height
console.log("img is:", width, '----',height)
if (width < 1200){
hint.value = "Images should be at least 1200px wide"
}else {
hint.value = ""
}
if (hint.value){
return
}
console.log("form is:", form.get('file'))
setTimeout(function (){
hint.value = "Server error"
}, 2000)
// after save success, return src to parent
// emit("save", "xxxxxxx.png")
}
})
}
}
</script>
<template>
<MModal
:model-value="isCropperVisible"
:hideCloseIcon="true"
maxWidth="90rem"
>
<template #header>
<div class="flex justify-center">
Customize your image
</div>
</template>
<template #body>
<Cropper
ref="cropper"
:src="src"
:stencil-component="RectangleStencil"
:stencil-props="{aspectRatio: 3}"
backgroundClass="background"
/>
<div v-if="hint" class="my-2 font-normal text-sm">
{{ hint }}
</div>
<div class="flex justify-end gap-4 mt-6">
<MButton
variant="secondary"
@click="cancel()"
class="md:!w-[8.4375rem]"
>
Cancel
</MButton>
<MButton
variant="primary"
@click="saveCropper"
class="md:!w-[12.3125rem]"
>
Create
</MButton>
</div>
</template>
</MModal>
</template>
cropper组件文档:https://advanced-cropper.github.io/vue-advanced-cropper/components/cropper.html#props
补充:
//cropper固定圆大小:
:stencil-size="{
width: 100,
height: 100,
}"
//限制最小裁剪宽度和高度
:min-width="200"
:min-height="200"
//下面是这个是一个官方的滚动条的例子
https://advanced-cropper.github.io/vue-advanced-cropper/guides/showcase.html#twitter
