html2canvas web page screenshot is not clear problem

Cause Analysis:

The devicePixelRatio property in the browser window determines that the browser will use several pixels to render a pixel. Assuming devicePixelRatio=2, under the retina screen, it will use a width of 2 pixels to render 1 pixel of the canvas, so The width and height that the canvas actually occupies on the retina screen is doubled, so the picture becomes blurry.

Solution: We can enlarge the coordinate system of the canvas, and then reduce the width and height of its display

var getPixelRatio = function(context) {
	var backingStore = context.backingStorePixelRatio ||
		context.webkitBackingStorePixelRatio ||
    	context.mozBackingStorePixelRatio ||
    	context.msBackingStorePixelRatio ||
    	context.oBackingStorePixelRatio ||
    	context.backingStorePixelRatio || 1;
	return (window.devicePixelRatio || 1) / backingStore;
};

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var scaleBy = getPixelRatio(context);
var w = 500;
var h = 500;
canvas.width = w * scaleBy;
canvas.height = h * scaleBy;
canvas.style.width = w + 'px';
canvas.style.height = h + 'px';
context.scale(scaleBy, scaleBy);
html2canvas(document.getElementById("posterImg"), {
    canvas:canvas,
    onrendered: function(canvas) {
        var dataUrl = canvas.toDataURL();
        var newImg = document.createElement("img");
        newImg.src =  dataUrl;
        newImg.width=w;
        newImg.height=h;
        $("body")[0].appendChild(newImg);
    }
});


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326440505&siteId=291194637