html2canvas生成截图(在uni-app中使用)

6,131 阅读1分钟

官方文档:html2canvas.hertzen.com/documentati…

  1. 安装 npm install html2canvas --save
  2. 使用 import html2canvas from 'html2canvas'
html2canvas(domName, {
            backgroundColor: null,// null 表示设置背景为透明色
            useCORS: true, // 是否尝试使用CORS从服务器加载图像
            allowTaint: true, //允许跨域(图片跨域相关),服务器也需要做相应的图片跨域处理
            taintTest: true, //是否在渲染前测试图片
            scale: 3, // dpr比列
            scrollY: 0 // 截屏时页面滚动,造成截屏图片不全或空白
            })
            .then(canvas => {
                let dataURL = canvas.toDataURL("image/png");
                console.log(dataURL)
            .catch(e => {
                console.log(e)
            });

3.图片跨域问题,需要后台也做跨域处理

在uni-app中使用 因为uni-app不能使用操作dom节点,所以要使用renderjs,画html和在vue中一样

// html
<view @click="html2canvas.create"> // 触发
    <u--image src="../../static/img/c-share.png" width="28" height="24"></u--image>
    <view class="text-center m-t-5">分享</view>
</view>
<script>
    methods: {
        renderFinish(opt) {
            uni.hideLoading()
            this.base64 = opt.path
        },
        showLoding() {
            this.isShowPoster = true
            uni.showLoading({
                    title: '图片生成中'
            })
        },
        hideLoading() {
                uni.hideLoading()
        },
        // 保存图片
        save() {
                const bitmap = new plus.nativeObj.Bitmap("test")
                bitmap.loadBase64Data(this.base64, function() {
		const url = "_doc/" + new Date().getTime() + ".png"; // url为时间戳命名方式
		bitmap.save(url, {
			overwrite: true, // 是否覆盖
			// quality: 'quality'  // 图片清晰度
		}, (i) => {
			uni.saveImageToPhotosAlbum({
                            filePath: url,
                            success: function() {
                                uni.showToast({
                                    title: '图片保存成功',
                                    icon: 'none'
                                })
                                bitmap.clear()
                            }
                        });
		}, (e) => {
			uni.showToast({
				title: '图片保存失败',
				icon: 'none'
			})
			bitmap.clear()
		});
	}, (e) => {
		uni.showToast({
			title: '图片保存失败',
			icon: 'none'
		})
		bitmap.clear()
	})
        },
    }
</script>
<script module="html2canvas" lang="renderjs">
	import html2canvas from 'html2canvas'
	export default {
		methods: {
			create() {
				this.$ownerInstance.callMethod('showLoding', true) // this.$ownerInstance.callMethod用于两个script之间交流
				const timer = setTimeout(async () => {
					try {
						const dom = document.getElementById('poster')
						const canvas = await html2canvas(dom, {
							width: dom.offsetWidth, //设置canvas尺寸与所截图尺寸相同,防止白边
							height: dom.offsetHeight, //防止白边
							logging: true,
							useCORS: true,
							allowTaint: true,
							scale: window.devicePixelRatio,
							dpi:300,
							scrollY: 0
						})
						console.log('canvas:', canvas)
						const base64 = canvas.toDataURL('image/png');
						this.$ownerInstance.callMethod('renderFinish', {
							path: base64
						})
						clearTimeout(timer)
					} catch (e) {
						this.$ownerInstance.callMethod('hideLoading', true)
						console.log(e)
					}
				}, 1000)
			}
		}
	}
</script>

出现DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported的错误,有一些原因是不能用uni-app框架image标签,改成img标签即可解决。