当前位置: 代码迷 >> 综合 >> vue项目中实现网页的截图功能 (html2canvas)
  详细解决方案

vue项目中实现网页的截图功能 (html2canvas)

热度:43   发布时间:2023-11-20 03:41:14.0

最近做地图的项目,有个需求就是前端需要将网页的内容生成一张图片,这个功能如果让后端做的话,前端需要把大量的代码传给后端,然后后端去解析生成图片,再返回给前端,幸运的是,html2canvas.js让这件事情变得简单起来,下面是我在vue项目中实现截图功能的代码:

一、先安装html2canvas

npm install html2canvas --save或者yarn add html2canvas

二、引入html2canvas

import html2canvas from 'html2canvas'

三、主要实现代码:

1、HTML中:

<template><!--超级地图--><div id="superMap"/><!--点击button即可实现页面的截图--><div id="test"><el-button @click="getImg">截图</el-button></div>
</template>

2、JavaScript中:

methods:{
    //截图方法getImg(){
    html2canvas(document.getElementById('superMap'),{
    backgroundColor:null,//画出来的图片有白色的边框,不要可设置背景为透明色(null)useCORS: true,//支持图片跨域scale:1,//设置放大的倍数}).then(canvas => {
    //截图用img元素承装,显示在页面的上let img = new Image();img.src = canvas.toDataURL('image/jpeg');// toDataURL :图片格式转成 base64document.getElementById('test').appendChild(img);//如果你需要下载截图,可以使用a标签进行下载let a = document.createElement('a');a.href = canvas.toDataURL('image/jpeg');a.download = 'test';a.click();})}}

四、在使用html2canvas时,估计大家可能会遇到下面的问题

1、图片跨域:如果需要截图的地方包含其他域名的图片,那么会出现跨域问题
解决:1)设置useCORS:true,2)把后端的图片转成base643)将图片都放在同一个域名下

2、画出来的图片有白色的边框
解决:
1)设置 backgroundColor: null

五、总结

当然本文只是关于html2canvas一小部分的配置的使用,具体可见官网:http://html2canvas.hertzen.com/documentation