vue 根据选择的图片绘制canvas图片及编辑

工具: cropperjs+vue+canvas

methods: {
        // 画图片方法
        drawImage(src) {
            this.$nextTick(function() {
                let img = new Image();
                // console.log("this.img is ",this.img);
                // 设置跨域必须放到img.src前面
                img.setAttribute('crossOrigin', 'anonymous');
                console.log("当前的图片的路径是:",this.imglist[this.index].path);
                img.src = src;
                const that = this;
                new Promise(function(resolve,reject) {
                    img.onload = function() {
                        console.log("in onload img is ",img.width,img.height);
                        let whRatio = img.width / img.height;
                        if((img.width / img.height) < (1006 / 674)) {
                            // 适配高度
                            img.height = 674;
                            img.width = whRatio * img.height;
                        } else {
                            // 适配宽度
                            img.width = 1006;
                            img.height = img.width / whRatio;
                        }
                        const myCanvas = that.$refs.crp;
                        console.log(myCanvas);
                        resolve(myCanvas);
                    }
                }).then((data) => {
                    let ctx = data.getContext('2d');
                    console.log("ctx is ",ctx);
                    ctx.clearRect(0,0,1006,674);
                    let offsetLeft = 1006 - img.width;
                    let offsetHeight = 674 - img.height;
                    ctx.drawImage(img, offsetLeft / 2, offsetHeight / 2, img.width, img.height);
                    if(that.cropper === '') {
                        that.cropper = new Cropper(data,{});
                    } else {
                        console.log("reset cropper");
                        that.cropper.destroy();
                        that.cropper = null;
                        that.cropper = new Cropper(data,{});
                    } 
                    console.log("canvas's data is ",that.cropper.getCanvasData());
                    console.log("this.cropper is ",that.cropper);
                })
            })
        },
        async activeTheImg(imgSrc,index) {
            console.log("imgSrc is ",imgSrc);
            console.log("index is ",index);
            this.currentIndex = index;
            this.img = this.imglist[index];
            await this.drawImage(this.img.path.replace('thumbnails/',''));
        },

当切换图片的时候将之前的canvas清空,然后将cropperjs 销毁重新建一个就会出现切换不同的图片都会绘制出来并且可以编辑了

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值