0、先下载是王道

npm install html2canvas


1、在 HTML 中标记指定要截图的元素

<!--选区(要截图的区域)设置 ref 属性-->
    <div ref="domToImg">
        <img src="a.png" alt="">
        <span>某标语</span>
        <img src="b.png" alt="某二维码">
    </div>


2、在 js 中,导入并使用 html2canvas

 import html2canvas from 'html2canvas'
 
    data () {
        return {
            htmlUrl: '' //接收生成图片的 url ,可以在html中使用img标签显示该图片
        }
    },
 methods: {
 //截图方法
 toImg () {
     // 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
     html2canvas(this.$refs.domToImg, {
     backgroundColor: null,
     useCORS: true // 如果截图的内容里有图片,可能会有跨域的情况,加上这个参数,解决文件跨域问题
            }).then((canvas) => {
                let url = canvas.toDataURL('image/png') // 最终生成图片的 url
                this.htmlUrl = url
            })
        }
    }

点赞(0)

评论列表 共有 0 条评论

暂无评论
立即
投稿
发表
评论
返回
顶部