Html2Canvas使用问题:如何截取指定DOM元素的中心区域内容
你需要在html2canvas的配置参数中新增x、y、width、height四个属性,指定要截取的区域相对于你当前选中的根元素(texera-workflow-editor)的偏移位置和尺寸即可。
具体操作:
- 先确定橙色线条之间的中心区域,相对于
texera-workflow-editor左上角的横向偏移量x、纵向偏移量y,以及该区域的实际宽度width、高度height。如果这个中心区域本身有独立的DOM节点,可以直接用getBoundingClientRect()方法自动获取对应数值,无需手动计算。
修改后的代码参考:
let doc = document.getElementById("texera-workflow-editor") || document.body; // 如果你要截取的中心区域有单独的DOM,替换下面的选择器即可,没有的话可以手动填写x/y/width/height的数值 const targetCenter = document.getElementById("你要截取的中心区域的DOM ID"); const targetRect = targetCenter.getBoundingClientRect(); const docRect = doc.getBoundingClientRect(); html2canvas(doc, { allowTaint: true, useCORS: true, backgroundColor: "rgba(0,0,0,0)", // 新增裁剪区域参数 x: targetRect.left - docRect.left, y: targetRect.top - docRect.top, width: targetRect.width, height: targetRect.height }).then(canvas => { // 原有后续逻辑保持不变 })
如果没有对应的独立DOM,你手动算好数值直接填入即可,比如要截取距离父元素左边缘30px、上边缘50px,宽800px高500px的区域,就直接写x: 30, y: 50, width: 800, height: 500。
内容的提问来源于stack exchange,提问作者qwertyasdf
相关产品推荐
相关产品推荐

