簡體   English   中英

使用html2canvas設置Png的質量

[英]Set Quality of Png with html2canvas

        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()的質量。 有什么方法嗎? 因為返回數據質量低。

簡短回答:
將圖像大小設置為原始大小的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() 
  }
});

工作中的JSBin鏈接

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

您可以在html2canvas中使用縮放選項。

在最新版本v1.0.0-alpha.1中,您可以使用scale選項來提高分辨率(scale:2將使分辨率從默認的96dpi翻倍)。

// Create a canvas with double-resolution.
html2canvas(element, {
    scale: 2,
    onrendered: myRenderFunction
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM