html2canvas截图生产海报图片


图片地址后添加?time=${new Date().valueOf()},不然会报图片跨域报错
原因:这是因为你img是在缓存数据中读取的 并没有访问远程这个图片的时候没有携带请求头。
确保你的图片服务器支持CORS访问,也就是会返回Access-Control-Allow-Origin等响应头;

import html2canvas from 'html2canvas'


       //响应式,高度根据宽度比例响应,定位
        makeDom(){
            let _this = this;
            this.$nextTick(function(){
                let poster = document.getElementById('poster');
                let posterWidth = poster.offsetWidth;
                let bgimg = document.getElementById('bgimg');
                let banner  = document.getElementById('banner');
                let title  = document.getElementById('title');
                let info  = document.getElementById('info');
                let infoavatar   = document.getElementById('infoavatar');
                let infocode   = document.getElementById('infocode');
                poster.style.height = posterWidth*1.35+'px';
                bgimg.style.height = posterWidth*1.35+'px';
                banner.style.top = posterWidth*0.5+'px';
                banner.style.height = posterWidth*0.4+'px';
                title.style.top = posterWidth*0.93+'px';
                info.style.top = posterWidth*1.05+'px';
                infoavatar.style.width = posterWidth*0.16+'px';
                infoavatar.style.height = posterWidth*0.16+'px';
                infocode.style.width = posterWidth*0.23+'px';
                infocode.style.height = posterWidth*0.23+'px';
                setTimeout(function() {
                   _this.makePoster();
                },2000)
            })
        },
        //生成图
        makePoster(){
            let that = this;
            html2canvas(this.$refs.poster, {
                backgroundColor: '#fff',
                useCORS: true,//开启跨域
                imageTimeout: 6000,
                logging: true,
                //allowTaint: true,
            }).then(canvas => {
                    let dataURL = canvas.toDataURL('image/png');
                    let file = that.base64toFile(dataURL)
                    //file就是图片,可做一个图片上传到自己的资源服务器
                }).catch((err) => {})
        },
        base64toFile(dataurl, filename = "file") {
            let arr = dataurl.split(",");
            let mime = arr[0].match(/:(.*?);/)[1];
            let suffix = mime.split("/")[1];
            let bstr = atob(arr[1]);
            let n = bstr.length;
            let u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], `${filename}.${suffix}`, {
                type: mime,
            });
        },

你可能感兴趣的:(#,小程序,前端)