一、项目背景
有时候前端遇到某些功能需要进行对当前页面或某些页面的元素进行截图,并生成预览图片。
二、项目技术
经过当前前端技术的调查,使用了 html2canvas 插件进行截图.
三、项目中html2canvas的时候
官方文档 地址
-
安装
npm install --save html2canvas
-
引入
import html2canvas from 'html2canvas';
-
使用
-
index.vue文件
<div id="picture"> <h4>Hello world!</h4> </div>
-
index.js
const divElement = document.getElementById('picture'); // 替换为你的 <div> 元素的 id const canvas = await html2canvas(divElement, { useCORS: true,// 使用跨域 }); canvas.toDataURL('image/png') // canvas 生成图片
-
-
总结
1. 进行截图的时候,如果html 页面上有图片 会有图片跨域问题。-
在使用 html2canvas 的时候 打开跨域属性 useCORS: true,
-
在个截图标签元素里面的 img 标签添加跨域属性 crossOrigin="anonymous"
-
当前方法既可以截取 私有桶的图片,也可以截取 公有桶的图片。
-