user3211337 user3211337 - 23 days ago 4
CSS Question

Javascript html2canvas cant get background

Some issues using Javascript library html2canvas. The problem is that html2canvas is getting "div2" with a transparent (sometimes white) background, I want to include the body background (or is behind this div) on "div2".

<div id="div2" style="width: 150px; height: 50px;"></div>


html2canvas(document.getElementById("div2"), {
onrendered: function(canvas) {
var photostring = canvas.toDataURL("image/png");
console.log(photostring);
}
});

Answer

Logically the rendering works from the element you select.

So will not get the background, unless you select the "parent element" or "root element".

I have two solutions:

1 - Using Javascript/Jquery you can capture X and Y position from div#target then you set background-image and background-position in div#target by X/Y position

2 - You capture <body> with html2canvas, then using canvas/javascript api you crop image by X/Y position and Width/Height from div#target, see example: #242 (comment) Note: set width/height/x/y in these variables (see example):

var targetDiv = $("#target");
var sourceX = targetDiv.position().left;/*X position from div#target*/
var sourceY = targetDiv.position().top;/*Y position from div#target*/
var sourceWidth = targetDiv.width();/*clientWidth/offsetWidth from div#target*/
var sourceHeight = targetDiv.height();/*clientHeight/offsetHeight from div#target*/

Get background-image in parent/root element:

https://github.com/niklasvh/html2canvas/commit/281e6bbedf9f611846eba3af4d256eb97f608aa2

Crop canvas:

https://github.com/niklasvh/html2canvas/issues/242#issuecomment-20875688

Comments