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