繁体   English   中英

html2canvas 和内联 SVG

[英]html2canvas and inline SVG

我正在尝试使用 html2canvas 从 div 中显示的内容创建 PNG 图像。 该 div 包含:

  • 更多带有文本内容的 div(被 html2canvas 捕获)
  • 像这样的内联 SVG 元素: <svg version="1.1" id="img-15" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 645 585" style="enable-background:new 0 0 512.001 512.001;" xml:space="preserve" class="svg replaced-svg"><path [...]/></svg> <svg version="1.1" id="img-15" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 645 585" style="enable-background:new 0 0 512.001 512.001;" xml:space="preserve" class="svg replaced-svg"><path [...]/></svg>

在使用 html2canvas 之前,这可能看起来像这样:

在此处输入图像描述

然后我使用以下代码生成 PNG 图像: html2canvas(document.querySelector("#monogram-zone"),{width:pWidth,height:pHeight,x:pLeft,y:pTop,backgroundColor:null}).then(canvas => { document.getElementById("monogram").appendChild(canvas); });

...结果如下:

在此处输入图像描述

问题:我的 SVG go 到哪里去了,如何让 html2canvas 将其与文本 div 一起捕获?

有点晚了......对于任何绊倒这个问题的人,可能是您对 svg 标签进行了转换。

出于某种原因,html2canvas 将转换重新应用于已经转换的元素。

这是一个说明问题的 JSFiddle: https://jsfiddle.net/vqnpx582/

使用 JSFiddle,因为下面的代码不起作用!

 window.takeScreenshot = () => { html2canvas(document.querySelector("#monogram-zone")).then(canvas => { document.getElementById("monogram").appendChild(canvas); }); }
 div div { font-size: 3rem; font-family: sans-serif; } #textOgray { color: #555; position: fixed; left: 20px; top: 30px; } #textamp { position: fixed; left: 50px; top: 37px; } #textO { position: fixed; left: 80px; top: 30px; } #monogram-zone { width: 160px; height: 90px; overflow: hidden; background-color: cyan; position: relative; }
 <script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script> <div id='monogram-zone'> <svg version="1.1" id="img-15" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewbox="-10 -10 100 50" xml:space="preserve" style="transform: translate3d(10px, 20px, 30px);" class="svg replaced-svg"> <path fill="red" stroke-width="10" stroke="red" d="M0 0 h300 100"/> </svg> <div id='textOgray'>O</div> <div id='textamp'>&amp;</div> <div id='textO'>O</div> </div> <button onclick="takeScreenshot()">to image</button> <div id="monogram" />

正如您在小提琴中看到的那样,当运行 html2canvas 时,红色条会第二次变换,移动到不同的位置。

这可能会导致某些元素从捕获的 div 中消失。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM