vue页面截图;H5页面截图;vue项目中将特定网页内容生成图片(截图);html2canvas截图

6 篇文章 0 订阅

功能
1.兼容 PC 和 Mobile;
2.对指定的区域进行截取;
3.可以控制截图大小;
4.截图生成base64图片地址
在这里插入图片描述

一、安装插件

npm install html2canvas --save  或 yarn add html2canvas

二、在.vue页面引入使用

import html2canvas from "html2canvas";

三、以下代码可直接复制

<template>
  <div id="page">
    <div>页面截图 只截取指定区域</div>

    <!-- 截图区域 -->
    <div class="content" ref="content">
      <div style="float:left">这里是丰富的网页内容...</div>
      <input type="text" style="width:300px;height: 30px;">
      <div style="height:100px">div盒子</div>
      <div style="height:100px">300px</div>
    </div>

    <button class="btn" @click="getPrintScreen">获取截图</button>
    <div class="img-box">
      <h2>截图结果:</h2>
      <!-- 通过img标签把获取到的截图呈现出来 -->
      <img :src="imgUrl" alt="" />
    </div>
  </div>
</template>

<script>
import html2canvas from "html2canvas"

export default {
  name: "Screenshot",
  data () {
    return {
      imgUrl: null, //截图地址
    }
  },
  methods: {
    //获取截图方法
    getPrintScreen () {
      // 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
      html2canvas(this.$refs.content, {
        // width: 30, //截图宽度
        // height: 50, //截图高度
        backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色(null)
        useCORS: true, //支持图片跨域
        scale: 1, //设置放大的倍数
      }).then((canvas) => {
        // 把生成的base64位图片上传到服务器,生成在线图片地址
        let url = canvas.toDataURL("image/png") // toDataURL: 图片格式转成 base64
        console.log('base64图片地址', url)
        this.imgUrl = url
      })
    },
  },
};
</script>


<!-- 本demo样式代码(不重要) -->
<style lang="less">
#page {
  padding: 0;
  width: 100%;
  height: 100%;
  background-color: #fff;
  .content {
    text-align: center;
    background-color: rgb(243, 161, 152);
  }
  .btn {
    display: block;
    width: 60vw;
    height: 50px;
    background: #79c76f;
    border-radius: 2vw;
    border: none;
    font-family: Source Han Sans CN;
    font-weight: 400;
    color: #ffffff;

    letter-spacing: 4px;
    text-align: center;
    margin: 30px 0 20px 40px;
  }
}
</style>

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值