加入几个Divs和出口图像为PNG HTML2Canvas

发布于 2025-01-26 05:52:15 字数 1126 浏览 3 评论 0原文

我正在尝试加入几个Divs,以将我的屏幕截图与HTML2Canvas一起屏幕截图。如果我仅将DIV用作HTML2Canvas的目标,则该库正常工作,但是一旦我尝试通过编码的方式加入多个Div,则图像与最后一个添加的Div。 DOM已更改,一切都在向下移动。

是为HTML2Canvas创建串联divs的正确方法吗?

我如何获得预期的结果?泰

var screenshot = document.getElementById("screenshotButton");

screenshot.addEventListener("click", function(event) {
  const captureElement = document.getElementById('cy')
  const testDiv = document.getElementById('tippy-2')

  var alpha = document.createElement("div");
  alpha.appendChild(captureElement);
  alpha.appendChild(testDiv);
  // document.body.appendChild(alpha);


  html2canvas(alpha)
  .then(canvas => {
    crossOriginIsolated = 'anonymous',
    useCORS= true,
    foreignObjectRendering= true,
    allowTaint =false,
    canvas.style.display = 'none'
    document.body.appendChild(canvas)
    return canvas
  })
  .then(canvas => {
    const image = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream')
    const a = document.createElement('a')
    a.setAttribute('download', 'my-image.png')
    a.setAttribute('href', image)
    a.click()
    canvas.remove()
  })

I am trying to concatenate several divs to take a screenshot of my screen with html2canvas. The library works correctly if I use just a div as target with html2canvas but once I try to concatenate several divs the way I coded it, the image is with the last added div. The DOM is altered and everything is moving down.

Is it the right way to create concatenate divs for html2canvas ?

How can I get the expected results ? ty

var screenshot = document.getElementById("screenshotButton");

screenshot.addEventListener("click", function(event) {
  const captureElement = document.getElementById('cy')
  const testDiv = document.getElementById('tippy-2')

  var alpha = document.createElement("div");
  alpha.appendChild(captureElement);
  alpha.appendChild(testDiv);
  // document.body.appendChild(alpha);


  html2canvas(alpha)
  .then(canvas => {
    crossOriginIsolated = 'anonymous',
    useCORS= true,
    foreignObjectRendering= true,
    allowTaint =false,
    canvas.style.display = 'none'
    document.body.appendChild(canvas)
    return canvas
  })
  .then(canvas => {
    const image = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream')
    const a = document.createElement('a')
    a.setAttribute('download', 'my-image.png')
    a.setAttribute('href', image)
    a.click()
    canvas.remove()
  })

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文