需求
個人需求是在手機頁面講一段html轉成圖片讓用戶能夠保存,因此以前那段html則不須要顯示了。css
正常渲染
使用html2canvas正常渲染出來在手機上顯示很是的模糊。代碼以下:html
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轉成了圖片canvas
優化app
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會把間距也渲染出來就很難處理了。dom
若是對你有幫助。或者想關注更多能夠看看博客優化