Home > Web Front-end > HTML Tutorial > How to generate high-definition images with html2canvas

How to generate high-definition images with html2canvas

高洛峰
Release: 2017-02-15 14:17:40
Original
2446 people have browsed it

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));

}

});
Copy after login

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");

}

});
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template