在一次开发中,微信端在商品详情页需要用到生成缩略图,然后分享的功能。
一开始想到的是用PHP的GD库实现。
然而本人是一个前端转后端的小白,对GD库一脸蒙蔽。
话不多说,介绍今天的主角 html2canvas.js (bootstrap cnd 有下载,这里就不贴地址了)。
DOM 结构
<div class="shareImageCon" id="shareImageCon"> <div class="head"> <div class="logo-con"> <img src="./logo.jpg" width="40" height="40" alt=""> </div> <div class="logo-text"> xxx微商城 </div> </div> <div class="main-img"> <img src="./phone.jpg" alt=""> </div> <div class="bottom"> <div class="ewm-img"> <img src="./ewm.gif" width="100" height="100" alt=""> </div> <div class="bottom-text"> <h3>舒肤佳纯白清香型沐浴露720ml舒肤佳纯白清香型沐浴露720ml</h3> <p class="price">¥17.00</p> </div> </div> <div class="tips">长按二维码识别购买</div> </div> <img src="" id="imgShow" alt="">
CSS样式
* { margin: 0; padding: 0; } .shareImageCon { width: 80%; margin: 0 auto; padding: 15px; background: #fff; } .shareImageCon .head { height: 40px; line-height: 40px; } .shareImageCon .head .logo-con, .shareImageCon .head .logo-text { float: left; font-size: 15px; } .shareImageCon .main-img img { width: 100%; height: 280px; } .shareImageCon .bottom { height: 100px; } .shareImageCon .bottom .ewm-img { float: left; width: 40%; } .shareImageCon .bottom .bottom-text { padding: 8px 0; float: left; width: 60%; font-size: 12px; color: #333; box-sizing: border-box; } .shareImageCon .bottom .bottom-text h3 { font-weight: normal; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; } .shareImageCon .bottom .bottom-text .price{ margin-top: 4px; font-size: 16px; color: rgb(223, 114, 85); } .shareImageCon .tips{ margin-top: 10px; width: 100%; text-align: center; font-size: 12px; color: #666; } #imgShow{ display: block; width: 90%; margin: 0 auto; }
js代码
var con = document.getElementById('shareImageCon'); var imgShow = document.getElementById('imgShow'); html2canvas( con, { onrendered: function(canvas){ var dataURL = canvas.toDataURL("image/png"); imgShow.src = dataURL; con.style.display = 'none'; } } )
这里是html2canvas的简单用法 英文好的大佬可以去 官网看文档 http://html2canvas.hertzen.com/;
本文结束,有不正确的地方欢迎指出。如有雷同,不胜荣幸。