使用vue制作h5页面,需求是生成带二维码的海报进行分享。
通过qrcodejs2生成指定url路径的二维码
通过使用html2canvas生成指定div的截图信息
问题:生成的海报模糊
不多废话直接贴关键代码
body部分:
<div class="poster_bg"> <div class="share_title"> <p style="margin: 0.5rem">长按图片保存并转发</p> <!-- <p style="margin-bottom: 0.5rem"></p>--> </div> <div class="gift-card" id="content" :style="hintBg" ref="content" > <img alt="logo" :src="getImgUrl(cardId)" @load="createPoster()" style="width: 90%;margin-top: 1rem"> <div class="gift-card-desc"> <div class="desc-left"> <span class="desc-title" >长按识别/扫描二维码</span> <br> <span class="desc-subtitle">即刻开启学霸之旅</span> </div> <div class="desc-right" id="qrcode"> </div> </div> </div> <img id="poster" alt="分享海报" :src="imgdata" v-show="this.loading" > </div>script部分
import html2canvas from "html2canvas"; import QRCode from "qrcodejs2"; export default { name: 'giftCardSales', data() { return { imgdata:null, descImg:[""], hintBg: { display: "flex" }, loading:false //是否已生成海报 } }, mounted() { // show //生成二维码 this.qrcode(); this.$nextTick(function(){ if(!this.loading){ console.log("nextTick") // this.createPoster() 调试用的 } }) }, methods: { getImgUrl(cardId) { return this.descImg[cardId]; }, getPrice(cardId) { return this.descPrice[cardId]; }, qrcode(){ let qrcode = new QRCode("qrcode", { text: "https://pay.xueba01.com/#/giftCardBuy?distriUserId="+this.userToken.user_id+"&cardId="+this.cardId, //URL地址 width: 70, height: 70, colorDark: '#000', //二维码颜色 colorLight: "#ffffff" , //背景颜色 correctLevel : QRCode.CorrectLevel.H //二维码纠错等级高 能纠正30% }); }, createPoster() { console.log("createPoster") // 生成海报 const shareContent = document.getElementById('content') var width = shareContent.offsetWidth; //获取dom 宽度 var height = shareContent.offsetHeight; //获取dom 高度 var canvas = document.createElement("canvas"); //创建一个canvas节点 const scale = 2; //定义任意放大倍数 支持小数 canvas.width = width * scale; //定义canvas 宽度 * 缩放 canvas.height = height * scale; //定义canvas高度 *缩放 var context = canvas.getContext('2d'); // 【重要】关闭抗锯齿 context.mozImageSmoothingEnabled = false; context.webkitImageSmoothingEnabled = false; context.msImageSmoothingEnabled = false; context.imageSmoothingEnabled = false; console.log(width) console.log(height) // 设置html2canvas方法的配置 var opts = { scale: scale, // 添加的scale 参数 canvas: canvas, //自定义 canvas // allowTaint: true, //允许画布上有跨域图片 不建议使用 后面详细补充 logging: true, //日志开关,便于查看html2canvas的内部执行流程 width: width, //dom 原始宽度 height: height, dpi:300, useCORS: true // 【重要】开启跨域配置 }; html2canvas(shareContent, opts).then(canvas => { this.imgdata = canvas.toDataURL('image/jpeg') var detail = document.getElementById('poster') detail.style.width = canvas.width / 2 + "px"; detail.style.height = canvas.height / 2 + "px"; this.loading=true // this.hintBg.display="none" }) } } }经过上述代码调试使得海报稍微清晰了一些不过还达不到原始的那么清晰,下面放一下对比效果图
参考链接:
高质量前端快照方案:来自页面的「自拍」
微信H5实现网页长按保存图片及识别二维码