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 销毁重新建一个就会出现切换不同的图片都会绘制出来并且可以编辑了

你可能感兴趣的:(Vue.js)