html2canvas不能识别svg中的图形,页面截取的图片,没有svg内容

html2canvas不能识别svg中的图形,页面截取的图片,没有svg内容

html2canvas 在默认设置下无法识别 SVG 中的内容。要想处理 SVG 中的图形,需要通过设置 html2canvas 的 foreignObjectRendering 选项为 true 来开启外部对象渲染,同时还需要在 svg 标签中添加 xmlns 属性以避免导出的图片文件无法识别 SVG 标记的问题。

以下是示例代码:

// 以异步方式获取生成图片所需的工具库
import html2canvas from 'html2canvas';
import { saveAs } from 'file-saver';

// 定义需要渲染为图片的元素,这里使用了一个包含 SVG 图形的 div 元素
const container = document.querySelector('#content');

// 开始渲染过程
html2canvas(container, { foreignObjectRendering: true }).then(canvas => {
  // 执行回调函数,导出图片
  canvas.toBlob(function(blob) {
    saveAs(blob, 'example.png');
  }, 'image/png');
});