Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

I wanna increase quality of canvasq.toDataURL(). Is there any Method ? Because Returned data low quality.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Short answer:
Set your image size to 1/3 of it's original size.

Long answer:
Print quality of images on your website is 72dpi.

When you try print your page, all texts are rendered as high quality vectors (normally ~300dpi, depending on your print settings).

So if you need to print out a high-quality image, you'll need to scale it down at least to a third of it's original size.

An when you're using html2canvas library to produce the image, you'll have to set all the CSS sizes to 300% before doing the render.

So consider this:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...