html2canvas使用记录

发布时间 2023-06-26 09:34:30作者: Merrys

1.生成图片有白边/黑边

设置 backgroundColor:#ffffff

2.本地生成图片没有白边/黑边,打包后生成图片有白边/黑边

查看打印容器/父级是否有定位,宽度过大/过小等,去掉定位或限宽

3.生成图片模糊

设置 scale参数

4.文字错位

设置字体

5.外链图片不显示

设置 useCors:true,同时将打印区的图片转为base64

6.safari 下设置图片名称有长度限制

7.获取不到容器,使用querySelector

例子:

const savePic = async () => {
   ....
        await qmsInventoryTablePreview(index)
        await getBase64Image()
        await html2canvas((document.body.querySelector('div#canvas-print') as HTMLDivElement).querySelector('.content'), {
            useCORS: true, scale: 3, backgroundColor: '#ffffff',

        }).then((canvas: any) => {
            let time = ((new Date()).toLocaleString()).slice(0, -3).replace(/\//g, '-')
            filename = filename ? filename : time + '_' + (document.getElementById('canvas-name') as HTMLElement).innerText
            setTimeout(() => {
                Canvas2Image.saveAsImage(canvas, canvas.width, canvas.height, 'jpg', filename);
            }, 100)
        })
    }
}
const getBase64Image = () => {
    return new Promise((res, _) => {
        let imgList = (document.body.querySelector('div#canvas-print') as HTMLDivElement).querySelectorAll('img')
        if (imgList.length == 0) return
        var img = document.createElement('img');
        img.src = imgList[0].src;
        img.setAttribute("crossorigin", "anonymous")
        img.onload = function () {
            var canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, img.width, img.height);
            var dataURL = canvas.toDataURL("image/png");
            (document.body.querySelector('div#canvas-print') as HTMLDivElement).querySelectorAll('img')[0].setAttribute('src', dataURL);
            res(true)
        }
    })
}
const savePdf = async () => {
    if (!inventoryDetail.value) return;
    let pages = A4Mode.value ? inventoryDetail.value!.length / 20 : 1
    for (let index = 1; index < pages + 1; index++) {
        ......
        await getBase64Image()
        await html2canvas((document.body.querySelector('div#canvas-print') as HTMLDivElement).querySelector('.content'), { backgroundColor: '#ffffff', useCORS: true, scale: 3, scrollX: 0, scrollY: 0 }).then((canvas: any) => {
            const PDF = new JsPDF('p', 'mm', 'a4')
            const ctx = canvas.getContext('2d')
            const a4w = 190;
            const a4h = 277;
            const imgHeight = Math.floor((a4h * canvas.width) / a4w)
            let renderedHeight = 0;
            while (renderedHeight < canvas.height) {
                const page = document.createElement('canvas');
                page.width = canvas.width
                page.height = Math.min(imgHeight, canvas.height - renderedHeight)
                page.getContext('2d')?.putImageData(ctx.getImageData(0, renderedHeight, canvas.height, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)
                PDF.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, (a4w * page.height) / canvas.width))
                renderedHeight += imgHeight;
                console.log(canvas.height)
                if (renderedHeight < canvas.height) {
                    PDF.addPage()
                }
            }
            let time = ((new Date()).toLocaleString()).slice(0, -3).replace(/\//g, '-')
            let filename = time + '_' + (document.getElementById('canvas-name') as HTMLElement).innerText 
            PDF.save(`${filename}.pdf`)
        })
    }
}