2013-08-19 69 views
2
 html2canvas($("#Element"), { 
    onrendered: function(canvasq) { 
    var w=window.open(); 
    w.document.write("<h3 style='text-align:center;'>"+ReportTitle+"</h3>"); 
    w.document.write("<img width='100%' height:'90%' src='"+canvasq.toDataURL()+"' />"); 
    w.print(); 
    } 
}); 

我想提高canvasq.toDataURL()的質量。 有什麼方法嗎?由於返回的數據質量低。用html2canvas設置PNG質量

+1

我在這裏有同樣的問題。在Safari html2canvas中工作得很好!但在Chrome中獲得的圖像非常低。有任何想法嗎? – RicardoGonzales

回答

5

簡短回答:
將您的圖像大小設置爲它的原始大小的1/3。

長答案:
您的網站上的圖像打印質量是72dpi。

當您嘗試打印您的頁面時,所有文本都呈現爲高質量矢量(通常爲〜300dpi,具體取決於您的打印設置)。

因此,如果您需要打印出高質量的圖像,則需要將其縮小到至少原始尺寸的三分之一。

當您使用html2canvas庫生成圖像時,您必須在執行渲染之前將所有CSS尺寸設置爲300%。

所以,可以這樣考慮:

var ReportTitle = 'Hello world!'; // For demonstration 

var bigCanvas = $("<div>").appendTo('body'); // This will be the 3x sized canvas we're going to render 
var scaledElement = $("#Element").clone() 
.css({ 
    'transform': 'scale(3,3)', 
    'transform-origin': '0 0' 
}) 
.appendTo(bigCanvas); 

var oldWidth = scaledElement.width(); 
var oldHeight = scaledElement.height(); 

var newWidth = oldWidth * 3; 
var newHeight = oldHeight * 3; 

bigCanvas.css({ 
    'width': newWidth, 
    'height': newHeight 
}) 

html2canvas(bigCanvas, { 
    onrendered: function(canvasq) { 
    var w=window.open(); 
    w.document.write("<h3 style='text-align:center;'>"+ReportTitle+"</h3>"); 
    w.document.write("<img width='"+oldWidth+"' height='"+oldHeight+"' src='"+canvasq.toDataURL()+"' />"); 
    w.print(); 
    bigCanvas.remove() 
    } 
}); 

Working JSBin link

+3

當我克隆元素時,html2canvas不起作用!爲什麼? – user2622044

+0

是否有關於此鏈接的任何關係https://github.com/niklasvh/html2canvas/issues/117 – user2622044

+0

任何人都可以確認此方法的工作原理嗎?克隆時,html2canvas有問題(可能是因爲克隆在dom上不可見) –

1

與CSS規模的做法是正確的。

首先我們需要放大元素 然後在「html2canvas」回調中將其縮小。

var ELEMENT = jQuery("#ELEMENT"); 

//get element width and height 
var w = ELEMENT.width(); 
var h = ELEMENT.height(); 

//scale up your element 
ELEMENT.css({ 
'transform': 'scale(3)', 
'-ms-transform': 'scale(3)', 
'-webkit-transform': 'scale(3)' }); 

//run html2canvas 
html2canvas(ELEMENT, { 
onrendered: function(canvas) { 

//scale back your element 
ELEMENT.css({ 
'transform': '', 
'-ms-transform': '', 
'-webkit-transform': '' }); 

//your actions to canvas 
var win = window.open(); 
win.document.write('<h3 style="text-align:center;">ttl</h3>'); 
win.document.write('<img width="100%" height:"90%" src="'+canvas.toDataURL()+'"/>'); 
win.print(); 


}, 
//set proper canvas width and height 
width: w*3, 
height: h*3 
}); 
+0

您不需要在jQuery中使用供應商前綴。此外,這並不適用於我,我不認爲html2canvas甚至支持任何CSS3轉換。 – Yeti