本次技术调研来源于H5项目中的一个重要功能需求:实现 这里有个栗子(请用微信打开,长按图片即可保存):3分钟探索你的知识边界 将整个网页保存为图片是一个十分有趣的功能,常见于H5活动页的结尾页分享。以下则是项目中调研和踩坑的一些小结和汇总。 一、实现HTML页面保存为图片1.1 已知可行方案现有已知能够实现网页保存为图片的方案包括:
1.2 解决方案的选择
1.3 html2canvas的使用方法
以下描述针对html2canvas版本是 1.3.1 实现保存为图片的第一步:html转为canvas基于 html2canvas(document.body).then(function(canvas) { document.body.appendChild(canvas); }); 1.3.2 实现保存为图片的第二步:canvas转image上一步生成的canvas即为包含目标元素的 这里的转换方案有
实际上, 二、生成图片的清晰度优化方案2.1 基础的清晰度优化方案
现有解决方案参考; 其基本原理为: 例如:希望在html中实际显示的 <canvas width="320" height="180" style="width:160px;height:90px;"></canvas> 参考上述文档具体的使用案例如下; convert2canvas() { var shareContent = YourTargetElem; var width = shareContent.offsetWidth; var height = shareContent.offsetHeight; var canvas = document.createElement("canvas"); var scale = 2; canvas.width = width * scale; canvas.height = height * scale; canvas.getContext("2d").scale(scale, scale); var opts = { scale: scale, canvas: canvas, logging: true, width: width, height: height }; html2canvas(shareContent, opts).then(function (canvas) { var context = canvas.getContext('2d'); var img = Canvas2Image.convertToImage(canvas, canvas.width, canvas.height); document.body.appendChild(img); $(img).css({ "width": canvas.width / 2 + "px", "height": canvas.height / 2 + "px", }) }); } 2.2 进阶的清晰度优化方案
实际在我们的项目中,即使作出 下面直接给出3条进一步的优化策略:
convert2canvas() { var cntElem = $('#j-sec-end')[0]; var shareContent = cntElem;//需要截图的包裹的(原生的)DOM 对象 var width = shareContent.offsetWidth; //获取dom 宽度 var height = shareContent.offsetHeight; //获取dom 高度 var canvas = document.createElement("canvas"); //创建一个canvas节点 var scale = 2; //定义任意放大倍数 支持小数 canvas.width = width * scale; //定义canvas 宽度 * 缩放 canvas.height = height * scale; //定义canvas高度 *缩放 canvas.getContext("2d").scale(scale, scale); //获取context,设置scale var opts = { scale: scale, // 添加的scale 参数 canvas: canvas, //自定义 canvas // logging: true, //日志开关,便于查看html2canvas的内部执行流程 width: width, //dom 原始宽度 height: height, useCORS: true // 【重要】开启跨域配置 }; html2canvas(shareContent, opts).then(function (canvas) { var context = canvas.getContext('2d'); // 【重要】关闭抗锯齿 context.mozImageSmoothingEnabled = false; context.webkitImageSmoothingEnabled = false; context.msImageSmoothingEnabled = false; context.imageSmoothingEnabled = false; // 【重要】默认转化的格式为png,也可设置为其他格式 var img = Canvas2Image.convertToJPEG(canvas, canvas.width, canvas.height); document.body.appendChild(img); $(img).css({ "width": canvas.width / 2 + "px", "height": canvas.height / 2 + "px", }).addClass('f-full'); }); }
.targetElem {width: 54px;height: 142px;margin-top:2px;margin-left:17px;transform: scale(0.5)} 三、含有跨域图片的配置由于canvas对于图片资源的 以下主要解决两类跨域的图片资源:包括已配置过CORS的 3.1 针对CDN中的图片的配置
var opts = {useCORS: true};html2canvas(element, opts);
3.2 针对微信用户头像的配置如果需要将 其他注意事项1. margin的遮挡问题微信中,唤出 2. 安卓版微信保存图片失败的问题
3. JPEG的黑屏问题设置 4. 不能保留动效在图片的 参考文献 |
|
来自: hncdman > 《print css》