var copyDom = document.querySelector('.fenxiang1'); var width = copyDom.offsetWidth;//dom宽 var height = copyDom.offsetHeight;//dom高 console.log(JSON.stringify(copyDom)); console.log(width); console.log(height); var scale = 2;//放大倍数 html2canvas(copyDom, { dpi: window.devicePixelRatio * 2, scale: scale, width, heigth: height,
useCORS:true
}).then(function (canvas) { var dataURL = canvas.toDataURL(); console.log(dataURL); that.canvas = dataURL.split(',')[1]; $(".i-d-canvas").attr('src', dataURL); myApp.preloader.hide(); api.addEventListener({ name: 'longpress' }, function (ret, err) { ac5.open(); }); });
<div class="i-d-fenxiang-canvas" v-if="isfenxiang"> <div class="i-d-fenxiang-close" @click="closeBanner"><i class="iconfont iconguanbi"></i></div>
//要放canvas的img
<img class="i-d-canvas" src=""> </div>
//要转化的弹窗开始 <!--分享弹窗开始--> <div id="win" class="i-d-fenxiang fenxiang1"> <img crossorigin="anonymous" class="i-d-fenxiang-pic" :src="fenxiang_pic" alt=""> <div class="i-d-fenxiang-box"> <div class="i-d-fenxiang-info"> <div class="i-d-fenxiang-info-name"> <i v-if="type==1" class="iconfont iconxiangqing-tm"></i> <i v-if="type==0" class="iconfont iconxiangqing-tb"></i> <i v-if="isbaoyou" class="iconfont iconxiangqing-baoyou"></i> {{name}} </div> <div class="i-d-fenxiang-price">现价:<span>¥{{yuan_price}}</span></div> <div class="i-d-fenxiang-quan"> <div class="i-d-fenxiang-quan-left"> <div>券</div> <div>{{quan}}</div> </div> <div class="i-d-fenxiang-quan-right"> 券后价:<span>¥{{xian_price}}</span> </div> </div> </div> <div class="i-d-fenxiang-right"> <div class="i-d-fenxiang-qrcord"> <!--<img class="i-d-fenxiang-qrcord-pic" :src="erweima" alt="">--> <div class="i-d-fenxiang-qrcord-pic" id="qrcode"></div> </div> <div class="i-d-fenxiang-qrcord-text">长按保存图片</div> <!--<button class="i-d-fenxiang-qrcord-btn">复制文案--> <!--</button>--> </div> </div> </div> <!--分享弹窗结束-->
用到的js:
<script src="http://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
注:处理img生成canvas时如果不是本地图片会有跨域问题,解决方法:
1、添加useCORS:true属性;
2、给要生成canvas的DOM中包含的每一个<img>标签添加crossorigin="anonymous"属性;
3、确保你的图片CDN服务器支持CORS访问,也就是会返回Access-Control-Allow-Origin等响应头;