【发布时间】:2021-11-19 07:48:40
【问题描述】:
我正在尝试在画布上呈现 HTML 元素。为此,我会预先计算 HTML 元素的大小,方法是将其附加到文档中,获取大小,然后稍后将其删除。
问题是,在 Chrome 中,我得到的尺寸太高了 200 像素。所以画布上的元素下面有一个巨大的空白。
我尝试过完全不使用任何字体设置,检查边距/填充(即使删除时也会出现同样的问题)并尝试使用 scrollHeight/offsetHeight/clientHeight/jQuery...都给出了太大的高度。我已经阅读了尽可能多的其他帖子,但没有得到解决方案。所以...希望有人能给我一些新的想法 :) 在 Firefox 中它可以完美运行...
代码如下:
function renderHTML(htmlContent, pageHeight, windowWidth, windowHeight, browserSettings, dPR) {
var containerDiv = document.createElement("div");
containerDiv.id = "container-div";
var fontSize = emToPx(parseFloat(browserSettings.plaintext.fontSize)); // This is 14px in the console
containerDiv.style.font = `${fontSize}px ${browserSettings.plaintext.fontFamily}`;
containerDiv.style.backgroundColor = "#fc0303";
containerDiv.innerHTML = htmlContent;
// Create a new HTML document to pass into drawDocument
var docToSign = document.implementation.createHTMLDocument();
docToSign.body.innerHTML = containerDiv.outerHTML;
docToSign.documentElement.style.backgroundColor = "#03fc07";
// Get size of doc
document.body.appendChild(containerDiv);
var docWidth = containerDiv.scrollWidth;
var docHeight = containerDiv.scrollHeight;
// containerDiv.parentNode.removeChild(containerDiv);
console.log("height: " + $("#container-div").height());
console.log("containerDiv.scrollHeight: " + containerDiv.scrollHeight);
console.log("containerDiv.offsetHeight: " + containerDiv.offsetHeight);
console.log("containerDiv.clientHeight: " + containerDiv.clientHeight);
console.log("docHeight: " + docHeight);
var canvas = initializeCanvas(docHeight, windowWidth, windowHeight, browserSettings, dPR, docWidth);
if (typeof canvas === "string") {
console.log(`renderHTML: Error when initializing the canvas.`);
return canvas;
}
console.log("canvas.width: " + canvas.width);
console.log("canvas.height: " + canvas.height);
...
控制台输出如下:
在画布上你可以看到一个巨大的差距:
红色是containerDiv 的背景,绿色是docToSign.documentElement 的背景。当我向docToSign.document.body 添加背景时,它的颜色不超过documentElement。所以,这些元素实际上都没有这么高。多余的空格是从哪里来的?
【问题讨论】:
标签: javascript html jquery css