Reputation: 426
I've set up html2canvas so I can edit text and then download that as image and that works great, but the size is limited to the width of its container.
If I set up canvas width and height render becomes that size but it's black. What am I doing wrong?
Here is the JSfiddle with everything working but if you add width and height (currently commented), rendered pictured will get black.
JavaScript
html2canvas(document.getElementById("imagewrap"), {
onrendered: function(canvas) {
canvas.className = "html2canvas";
// canvas.width = "1080";
// canvas.height = "1920";
document.getElementById("canvasWrapper").appendChild(canvas);
var image = canvas.toDataURL("image/png");
document.getElementById("downloadLink").href = image;
},
useCORS: true
});
Upvotes: 2
Views: 4897
Reputation: 36
Maybe this will help someone having the same issue as I; Try dividing your target size by the width of the source size, and then use that value as your scale. To clarify:
{
width: 1080,
height: 1080,
scale: 1
}
The code above would render a 1080x1080 image, however the actual html content would be contained to 348x348(source size) and surrounded by whitespace.
Instead I divided target/source (1080/348) and got 3.10344828. So, instead of setting the width and height I simply set the scale to 3.10344828 and the image outputted a perfect 1080x1080 image.
{
/*no width no height set*/
scale: 3.10344828
}
Upvotes: 1
Reputation: 5081
After creating a new <canvas>
element and setting the width
and height
attributes, the image is drawn on the canvas using the drawImage()
method [1].
html2canvas(document.getElementById("imagewrap"), {
onrendered: function(canvas) {
var _canvas = document.createElement("canvas");
_canvas.setAttribute('width', 1080);
_canvas.setAttribute('height', 1920);
var ctx = _canvas.getContext('2d');
ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, 1080, 1920);
var dataURL = _canvas.toDataURL();
document.getElementById("canvasWrapper").appendChild(_canvas);
var image = _canvas.toDataURL("image/png");
document.getElementById("downloadLink").href = image;
},
useCORS: true
});
Copy the JavaScript code below without disturbing your current work on JSFiddle and click the Download button to download the image. Then review the properties and content of the downloaded image:
Upvotes: 2