Home > Article > Web Front-end > How to generate high-definition images with html2canvas
Requirements
My requirement is to convert a piece of html into a picture on the mobile page so that the user can save it, so the previous piece of html does not need to be displayed.
Normal rendering
Using html2canvas to render normally will appear very blurry on the mobile phone. The code is as follows:
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)); } });
In the example, the plug-in canvas2image.js is also used to convert the canvas into a picture
Optimization
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"); } });
The definition is almost the same as the original dom definition. The pitfall here is that the position of the dom needs to start at the upper left corner, otherwise the rendered canvas will also render the spacing and it will be difficult to deal with.
For more html2canvas how to generate high-definition images related articles, please pay attention to the PHP Chinese website!