需求
我的需求是在手机页面讲一段html转成图片让用户可以保存,所以之前那段html则不需要显示了。
正常渲染
使用html2canvas正常渲染出来在手机上显示非常的模糊。代码如下:
var dom = $("#id"); html2canvas(dom[0], { canvas: canvas, onrendered: function (canvas) { $(dom).css("display", "none"); $(".img-container").append(Canvas2Image.convertToImage(canvas, width * scaleBy, height * scaleBy, type)); } });
例子中还用了插件canvas2image.js将canvas转成了图片
优化
var dom = $(".content-container .show-content"); var width = dom.width(); var height = dom.height(); var type = "png"; var scaleBy = 3; var canvas = document.createElement('canvas'); canvas.width = width * scaleBy; canvas.height = height * scaleBy + 35; canvas.style.width = width * scaleBy + 'px'; canvas.style.height = height * scaleBy + 'px'; var context = canvas.getContext('2d'); context.scale(scaleBy, scaleBy); context.font = 'Microsoft YaHei'; html2canvas(dom[0], { canvas: canvas, onrendered: function (canvas) { var all_width = $(window).width(); $("#content-container").css("display", "none"); $(".img-container").append(Canvas2Image.convertToImage(canvas, width * scaleBy, height * scaleBy, type)); $(".img-container img").css("width", all_width + "px").css("height", "aotu"); } });
这样清晰度几乎和原dom清晰度一样,这里有个坑就是dom的位置需要在左上角开始位置,不然渲染的canvas会把间距也渲染出来就很难处理了。
更多html2canvas 如何生成高清图片 相关文章请关注PHP中文网!