问题描述
使用Javascript库html2canvas的一些问题。问题是,html2canvas正在获得带有透明(有时是白色)背景的div2,我想在div2上包含body背景(或者在div之后)。
< div id =div2style =width:150px; height:50px;>< / div>
html2canvas(document.getElementById(div2),{
onrendered:function(canvas){
var photostring = canvas.toDataURL(image / png );
console.log(photostring);
}
});
逻辑上,渲染从您选择的元素。 / p>
所以不会得到背景,除非你选择父元素或根元素。
我有两个解决方案:
1 - 使用Javascript / Jquery,您可以从div#target
捕获X和Y位置设置背景图像和背景位置在div#target by X / Y位置
2 - 您捕获 ; body>使用html2canvas,然后使用
canvas / javascript api
按X / Y位置裁剪图片,并从div#target裁剪宽度/高度,示例:#242(comment)
注意:在这些变量中设置width / height / x / y(参见示例):
var targetDiv = $(#target);
var sourceX = targetDiv.position()。left; / * X位置从div#target * /
var sourceY = targetDiv.position()。
var sourceWidth = targetDiv.width(); / * clientWidth / offsetWidth from div#target * /
var sourceHeight = targetDiv.height(); / * clientHeight / offsetHeight from div#target * /
在父级/根元素中获取背景图片:
裁剪画布:
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);
}
});
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#targetthen 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
这篇关于Javascript html2canvas无法获得背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!