Javascript html2canvas cant get background

岁酱吖の 提交于 2019-12-24 05:17:07

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/22461108/javascript-html2canvas-cant-get-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!