记一次修改 html2canvas 源码

后台管理系统中,引入 html2canvas 制作封面图,结果总是出现位置的偏差。
经过刨源码发现,clone 出来的元素与源元素的位置产生了偏差,具体原因不明。
临时方案,缓存源元素的位置信息,在获取 clone 元素的位置信息时,判定是否产生了偏差,如果有偏差则记录。最终计算所有节点的位置信息时,减去偏差的值。

// 100 行左右 Bounds.fromClientRect 方法
Bounds.fromClientRect = function(clientRect) {
    // #start fixed by hxy 补充一下误差
    var left = clientRect.left
    if (window._html2canvas_diff_) {
        left = clientRect.left - window._html2canvas_diff_
    }
    // #end
    return new Bounds(left, clientRect.top, clientRect.width, clientRect.height);
};
// 4535 行左右 parseTree 方法
var parseTree = function(element) {
    // #start fixed by hxy 缓存一下误差
    var rootElementRect = element.getBoundingClientRect()
    if (rootElementRect.left !== window._html2canvas_.left) {
        window._html2canvas_diff_ = rootElementRect.left - window._html2canvas_.left
    } else {
        window._html2canvas_diff_ = 0
    }
    // #end
    var container = createContainer(element);
    container.flags |= 4 /* CREATES_REAL_STACKING_CONTEXT */ ;
    parseNodeTree(element, container, container);
    return container;
};
// 6960 行左右 renderElement 方法 case 0
ownerDocument = element.ownerDocument;
if (!ownerDocument) {
    throw new Error("Element is not attached to a Document");
}
defaultView = ownerDocument.defaultView;
if (!defaultView) {
    throw new Error("Document is not attached to a Window");
}
instanceName = (Math.round(Math.random() * 1000) + Date.now()).toString(16);
_a = isBodyElement(element) || isHTMLElement(element) ? parseDocumentSize(ownerDocument) : parseBounds(element), width =
    _a.width, height = _a.height, left = _a.left, top = _a.top;
// #start fixed by hxy 在这里缓存下真实的 DOM 位置
window._html2canvas_ = _a
// #end
defaultResourceOptions = {
    allowTaint: false,
    imageTimeout: 15000,
    proxy: undefined,
    useCORS: false
};
posted @ 2021-04-29 10:52  月半流云  阅读(337)  评论(0编辑  收藏  举报