废话就不说啦,直接上代码
1、安装组件、导入组件
npm install html2canvas --save
import html2canvas from 'html2canvas'export default {components: {html2canvas}}
2、页面:定义需要截图的标签,给一个id
<div id="capture"><!--在这里编写需要截图的页面代码--></div><button @click="doCut()">点击截图</button>
3、js方法实现
doCut() {html2canvas(document.querySelector('#capture')).then((canvas) => {const img = new Image()img.src = canvas.toDataURL('png')img.setAttribute('crossOrigin', 'anonymous')canvas.height = 500 // 自定义图片宽度var context = canvas.getContext('2d')img.onload = function(){var w = img.widthvar h = img.heightcontext.drawImage(img, 0, 0, w, h, 0, 0, w, h)var imgUrl = canvas.toDataURL('image/png')// 根据生成的图片地址imgUrl(base64)进行后续保存操作}})}
如果对你有帮助,顺手点个赞呗