Search code examples
html2canvas

html2canvas doesn't render image at top left


I have a chart in my web page and I use html2canvas to extract it into image. The extracted image quality is blurry and I want to increase its quality by rendering it 4 times bigger in size.

Normal function:

function exportChart() {
html2canvas($("[id$='extract']"), {
    onrendered: function (canvas) {
        var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
        var a = document.createElement('a');
         a.href = image;
         a.download = 'chart.png';
         a.click();
    }
});

Bigger size function:

function exportChart(e) {
var scaleBy = 4;
var w = 1000;
var h = 1000;
var div = document.querySelector('#extract');
var canvas = document.createElement('canvas');
canvas.width = w * scaleBy;
canvas.height = h * scaleBy;
canvas.style.width = w + 'px';
canvas.style.height = h + 'px';
var context = canvas.getContext('2d');
context.scale(scaleBy, scaleBy);

html2canvas(div, {
    canvas:canvas,
    onrendered: function (canvas) {
        var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); 
        var a = document.createElement('a');
         a.href = image;
         a.download = 'chart.png';
         a.click();
    }
});

The result is I got better quality image but it's not placed at top left which doesn't happen for the normal function. How do I make the bigger image (right side) placed right at top left? For your reference


Solution

  • It turns out that the context.scale() function also alter the starting position of Image inside the canvas.

    Thus we will get the result as I describe.