广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >如何用vue实现网页截图你知道吗
  • 921
分享到

如何用vue实现网页截图你知道吗

2024-04-02 19:04:59 921人浏览 独家记忆
摘要

目录1、安装html2canvas2、在需要的Vue组件中引入3、编写一个截图按钮4、调用函数toImage总结 1、安装html2Canvas npm install html

1、安装html2Canvas


npm install html2canvas --save

2、在需要的vue组件中引入


import html2canvas from "html2canvas";

3、编写一个截图按钮


<el-button class="button-dalod" size="mini" title="生成图片" @click="toImage()" icon="el-icon-download"></el-button>

4、调用函数toImage


// 页面元素转图片
        toImage () {
            // 手动创建一个 canvas 标签
            const canvas = document.createElement("canvas")
            // 获取父标签,意思是这个标签内的 DOM 元素生成图片
            // imageTofile是给截图范围内的父级元素自定义的ref名称
            let canvasBox = this.$refs.imageTofile
            // 获取父级的宽高
            const width = parseInt(window.getComputedStyle(canvasBox).width)
            const height = parseInt(window.getComputedStyle(canvasBox).height)
            // 宽高 * 2 并放大 2 倍 是为了防止图片模糊
            canvas.width = width * 2
            canvas.height = height * 2
            canvas.style.width = width + 'px'
            canvas.style.height = height + 'px'
            const context = canvas.getContext("2d");
            context.scale(2, 2);
            const options = {
                backgroundColor: null,
                canvas: canvas,
                useCORS: true
            }
            html2canvas(canvasBox, options).then((canvas) => {
                // toDataURL 图片格式转成 base64
                let dataURL = canvas.toDataURL("image/png")
                console.log(dataURL)
                this.downloadImage(dataURL)
            })
        },
        //下载图片
        downloadImage(url) {
            // 如果是在网页中可以直接创建一个 a 标签直接下载 
            let a = document.createElement('a')
            a.href = url
            a.download = '首页截图'
            a.click()
        },

别忘了给页面所在截图范围内的父级添加ref属性,方便canvas找到父级计算宽高从而截屏

这就是截图出来的效果:

 

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!

--结束END--

本文标题: 如何用vue实现网页截图你知道吗

本文链接: https://www.lsjlt.com/news/157564.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作