1.安装html2canvas插件

npm install --save html2canvas

2.在需要用到的.vue文件中引入

import html2canvas from 'html2canvas'

3.代码片段
说明:如果要被生成图片的dom是超出屏幕需要滚动才能查看的话,需要加上width,height windowWidth,windowHeight 这些属性才能保证截图的完整性, windowHeight的值用document.body.scrollHeight也行,具体看需求如何。

<template>
	<div>
		<button @click="createImg">生成图片并下载到本地</button>
		<button @click="saveImg">生成图片并上传到服务器</button>
		<div ref="content" style="width:200px;height:200px;border:1px solid #333333;">
			此dom是要被保存成图片的
		</div>
	</div>
</template>
<script>
	import html2canvas from 'html2canvas'
	export default {
		data(){
			return {
			}
		},
		methods:{
			createImg(){
				let content = this.$refs.content
				let scrollHeight = content.scrollHeight
				let scrollWidth = content.scrollWidth
				html2canvas(content,{
						scale: window.devicePixelRatio*2,
						useCORS: true , //开启跨域配置,但和allowTaint不能共存
						width:scrollWidth,
						height:scrollHeight,
						windowWidth:scrollWidth,
						windowHeight:scrollHeight,
						x:0,
						y:window.pageYOffset
					}).then((canvas) => {
						this.operType = 'edit'
						let dataURL = canvas.toDataURL("image/jpg");
						let link = document.createElement("a");    
						link.href = dataURL;
						let filename = `${new Date().getTime()}.jpg`;  //文件名称
						link.setAttribute("download", filename);
						link.style.display = "none"; //a标签隐藏
						document.body.appendChild(link);
						link.click();
					})
			},
			saveImg(){
				html2canvas(this.$refs.content,{
					scale: window.devicePixelRatio*2,
					useCORS: true , //开启跨域配置,但和allowTaint不能共存
					width:content.scrollWidth,
					height:content.scrollHeight,
					windowWidth:content.scrollWidth,
					windowHeight:content.scrollHeight,
					x:0,
					y:window.pageYOffset
				}).then((canvas) => {
					let dataURL = canvas.toDataURL("image/png");
					this.operType = 'edit'
					let filename = `${new Date().getTime()}.png`;
					let file_url = dataURLtoFile(dataURL, filename,"image/png"); //将文件转换成file的格式,就可以使用file_url传递给服务端了
					
					let formData = new FormData()
					formData.append('file',file_url)
					
					//这个uploadFile 根据自己上传接口的名字写
					uploadFile(formData).then(res=>{
						//此处具体业务具体操作
					})
				});
			},
			//将base64格式转换成file的格式
			dataURLtoFile(base64, filename,contentType) { 
				let arr = base64.split(',')  //去掉base64格式图片的头部
				let bstr = atob(arr[1])   //atob()方法将数据解码
				let leng = bstr.length
				let u8arr = new Uint8Array(leng)
				while(leng--){
					u8arr[leng] =  bstr.charCodeAt(leng) //返回指定位置的字符的 Unicode 编码
				}
				return new File([u8arr],filename,{type:contentType}) 
			}
		}
	}
</script>

4.具体的属性可以参考官方文档
5.小记

//1. 生成的背景默认为白色,可以通过 backgroundColor 属性修改背景颜色
html2canvas(this.$refs.content, {
  backgroundColor: null // null 表示设置背景为透明色
}.then(img => {});

//2.截图有时会错位,是因为不支持某些css属性造成的,调整css样式即可,有时margin 也会有影响。

6.补充
在移动端H5使用中,会有ios截图失效问题,目前的解决方案是 修改html2canvas版本为1.0.0
调用方法如下:

    (window.html2canvas || html2canvas)(content,
    {
      scale: window.devicePixelRatio, //window.devicePixelRatio * 2
      useCORS: true, //开启跨域配置,但和allowTaint不能共存
      width: scrollWidth,
      height: scrollHeight,
      windowWidth: scrollWidth,
      windowHeight: scrollHeight,
      x: 0,
      y: 0
    }).then(canvas => {
      let url = canvas.toDataURL("image/jpg");
      console.log(url)
      this.picUrl = url
    })
    .catch(err => {
      // do sth
    });
Logo

前往低代码交流专区

更多推荐