使用html2canvas踩坑,关于ignoreElements回调

276 阅读1分钟

这个回调非常奇怪,它默认遍历整个dom树,并且在存在回调的时候,只要在dom树某一层都不返回false就会直接停止遍历,想要拿到正确的dom节点,我的方法是直接插入到body上,并且加上id,这样在遍历的时候,可以先查询到body,在通过id查询到需要的dom节点,最后在通过compareDocumentPosition将目标盒子的子盒子添加进去

总而言之就是凑合用,没弄懂,以后会找时间搞明白

// 看看有没有拿来转canvas的dom,没有就创建一个
function main() {
    let box = document.querySelector("#map-mark-canvas-box");
    if (!box) {
        box = await getDom();
        document.body.append(box);
    }
    const canvas = await getCanvas1(box, item.name);
}

// 详细创建过程
function getDom() {
const box = document.createElement("div");
    // 样式在assets/style/common.less
    box.id = "map-mark-canvas-box";
    const canvas = document.createElement("canvas");
    canvas.width = 100;
    canvas.height = 120;
    //把canvas放入body中
    box.append(canvas);
    //创建画笔
    const context = canvas.getContext("2d");
    //设置起点 x,y
    context.moveTo(0, 120);
    context.lineTo(65, 19);
    context.lineTo(100, 19);
    context.strokeStyle = "#03FBFF";
    context.stroke();

    const div = document.createElement("div");
    div.innerHTML = `<div style="padding: 9px 8px 9px 11px;display: flex;align-items: center;border-right: 1px dashed rgba(3,251,255,0.3)">
       <svg
         width="12"
         height="12"
         viewBox="0 0 12 12"
         fill="none"
         xmlns="http://www.w3.org/2000/svg"
       >
         <rect
           x="6.24268"
           y="2"
           width="6"
           height="6"
           transform="rotate(45 6.24268 2)"
           fill="#0A1A34"
           stroke="#F6DE00"
           stroke-width="2"
         />
       </svg>
       <span id="map-mark-text" style="margin-left: 4px;color: #f6de00;"></span>
     </div>
     <div style="width: 35px;height: 100%;display: flex;align-items: center;justify-content: center;">
       <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"></svg>
     </div>`;
    div.classList.add("textBox");
    box.append(div);
    return box;
}

// 转换canvas
async function getCanvas1(dom, text) {
    if (!dom) {
        return console.log("dom不存在" + dom);
    } else {
        document.querySelector("#map-mark-text").innerHTML = text;
    }
    const c = await html2canvas(dom, {
        allowTaint: true,
        useCORS: true,
        backgroundColor: null,
        ignoreElements: (element) => {
            if (element === document.body) return false;
            if (element.id === "map-mark-canvas-box") return false;
            if (element.compareDocumentPosition(dom) === 10) return false;
            return true;
        }
    });
    console.log(c);
    return c;
}