vue-cropper图片裁剪

1,053 阅读1分钟

vue-cropper官网 github.com/xyxiao001/v…

安装vue-cropper npm install vue-cropper --save

<template>
    <ul>
        <li>
            <button @click="selectImg">本地上传图片</button>
            <input
                type="file"
                v-show="false"
                accept="image/*"
                @change="handleChange"
                ref="fileinput"
            />
            <p>不超过2M的png、jpg图片、gif图片</p>
        </li>
        <li class="cropBox">
            <vueCropper
                ref="cropper"
                :img="option.img"
                :output-size="option.size"
                :output-type="option.outputType"
                :info="true"
                :full="option.full"
                :can-move="option.canMove"
                :can-move-box="option.canMoveBox"
                :fixed-box="option.fixedBox"
                :original="option.original"
                :auto-crop="option.autoCrop"
                :auto-crop-width="option.autoCropWidth"
                :auto-crop-height="option.autoCropHeight"
                :center-box="option.centerBox"
            ></vueCropper>
        </li>
        <li>
            <p @click="save">保存</p>
        </li>
    </ul>
</template>
<script>
import { VueCropper } from "vue-cropper";
export default {
    components: { VueCropper },
    data() {
        return {
            option: {
                img: "", // 裁剪图片的地址
                size: 1, // 输出图片压缩比
                outputType: "png", // 裁剪生成图片的格式
                canScale: true, // 是否开启滚轮放大缩小
                autoCrop: true, //是否自成截图框
                // 只有自动截图开启 宽度高度才生效
                autoCropWidth: 135, // 默认生成截图框宽度
                autoCropHeight: 80, // 默认生成截图框高度
                fixed: true, // 是否开启固定宽高比
                fixedNumber: [16, 9], // 截图框 宽高比 w/h
                fixedBox: false, // 固定大小 禁止改变截图框大小
                full: false, //输出截图是否缩放
                canMove: true, // 能否拖动图片
                canMoveBox: true, //能否拖动截图框
                original: false, //上传图片按照原始比例显示
                centerBox: false, //  截图框能否超过图片
            },
            configinfo: {},
        };
    },
    created() {
        this.initData();
    },
    methods: {
    	// 获取图片信息
        initData(){
    		axios.get('/api/geturl').then(res => {
                    if(res.code == 200){
                        this.configinfo = {
                            Id: config.Id,
                            Content: config.Content,
                        };
                        this.option.img = this.configinfo.Content;
                        //设置裁剪区域的宽高为图片真实宽高
                        let image = new Image();
                        let that = this;
                        image.src= this.option.img;
                        image.onload=function(){
                            that.option.autoCropWidth = image.width;
                            that.option.autoCropHeight = image.height;
                        };
                    }
        	})        	
        },
        selectImg(e) {
            if (e.target !== this.$refs.fileinput) {
                e.preventDefault();
                if (document.activeElement !== this.$refs) {
                    this.$refs.fileinput.click();
                }
            }
        },
        // 检测选择的文件是否合适
        checkFile(file) {
            let that = this, { lang, maxSize } = that;
            // 仅限图片
            if (file.type.indexOf("image") === -1) {
                that.hasError = true;
                that.errorMsg = lang.error.onlyImg;
                return false;
            }
            // 超出大小
            if (file.size / 1024 > maxSize) {
                that.hasError = true;
                that.errorMsg = lang.error.outOfSize + maxSize + "kb";
                return false;
            }
            return true;
        },
        // 上传图片时设置图片源
        setSourceImg(file) {
            let that = this;
            let reader = new FileReader();
            reader.onload = function (e) {
                that.option.img = reader.result;
                //设置裁剪区域的宽高为图片真实宽高
                let image = new Image();
                image.src= reader.result;
                image.onload=function(){
                    that.option.autoCropWidth = image.width;
                    that.option.autoCropHeight = image.height;
                };
            };
            reader.readAsDataURL(file);
        },
        handleChange(e) {
            let that = this;
            e.preventDefault();
            if (this.loading !== 1) {
                let files = e.target.files || e.dataTransfer.files;
                if (this.checkFile(files[0])) {
                    this.setSourceImg(files[0]);
                }
            }
        },
        save() {
            if(this.option.img){
                this.$refs.cropper.getCropData((data) => {
                this.configinfo.Content = data;
                let obj = {
                    Id: this.configinfo.Id,
                    Content: this.configinfo.Content,
                };
                // 更换图片后,接口一定要放在getCropData()方法内,否则图片地址还是原来的
                axios.post('/api/posturl', obj).then(res => {
                    if (res.Code == 200) {
                        this.showMsg("success", "保存成功");
                    }
                })
                });
            }else{
                let obj = {
                    Id: this.configinfo.Id,
                    Content: '',
                };
                axios.post('/api/posturl', obj).then(res => {
                    if (res.Code == 200) {
                      this.showMsg("success", "保存成功");
                    }
                })
            }

        },
    },
};
</script>
<style>
.cropBox {
    width:340px;
    height:200px;
    overflow: hidden;
}
</style>