緣由分析:javascript
瀏覽器window中的devicePixelRatio屬性決定了瀏覽器會用幾個像素點來渲染一個像素,假設devicePixelRatio=2,在retina屏下,會用2個像素點的寬度去渲染canvas的1個像素點,所以該canvas在retina屏幕上實際佔據的寬高放大了一倍,所以圖片會變得模糊。html
解決:咱們能夠放大canvas的座標系,而後縮小其顯示的寬高java
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); } });