解决html2canvas无法下载svg的问题

854 阅读1分钟

说明

截取网页中部分元素,使用html2canvas时,如果元素中包含svg,那么下载的图片中不会显示svg部分,我们可以使用canvg将svg转为canvas然后下载,但是因为canvas版本更新,许多攻略过时,因此发出最新版本的canvg解决html2canvas下载svg不显示的代码实现。

版本说明

canvg:4.0.1 html2canvas 1.4.1

代码实现

1.遍历所有svg,用canvg替换svg为canvas

在svg的位置新增canvas,配置好canvas的位置

    let svgElements = document.body.querySelectorAll(`${domId} svg`);
    svgElements.forEach((item)=>{
        let canvas = document.createElement('canvas'); 
        canvas.width = item.getBoundingClientRect().width;
        canvas.height = item.getBoundingClientRect().height;
        const ctx = await canvas.getContext('2d');
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(canvas.width, canvas.height);
        ctx.stroke();
        ctx.closePath();
        const v = await Canvg.fromString(ctx, svg);
        await v.render();
    
        if (item.style.position) {
            canvas.style.position += item.style.position;
            canvas.style.left += item.style.left;
            canvas.style.top += item.style.top;
        }
        
    })
    

2.使用html2canvas下载图片

html2canvas(document.querySelector(domId), {...}).then(...)

3.删除新建的canvas

document.querySelectorAll(`${domId} canvas`).forEach(item => {
    item.remove();
});

源码

svg-cut-out - npm (npmjs.com)