vue使用html2canvas實現移動端H5頁面截圖


html2canvas能夠實現在用戶瀏覽器端直接對整個或部分頁面進行截屏。這個html2canvas腳本將當頁面渲染成一個Canvas圖片,通過讀取DOM並將不同的樣式應用到這些元素上實現。它不需要來自服務器任何渲染,整張圖片都是在客戶端瀏覽器創建。

點擊查看:官方文檔

點擊查看:線上demo

安裝引用html2canvas

npm install html2canvas
 
import html2canvas from 'html2canvas';

實現代碼

<template>
  <div id="pageDiv" :style="{'padding-top':isWeiXin || isApps?'0':'3rem'}">
 
    <!-- 頁面頭部-->
    <header-com :poptitle="'html2canvas截圖'" :type="'doc_title'" v-if="!isWeiXin && !isApps"></header-com>
    <!-- 頁面的主要內容 -->
    <section class="content">
      <div class="qr-code-box" ref="imageToFile">
        <vue-qr :logoSrc="config.logo" :text="config.value" class="qr-code-pic" :correctLevel="3" :margin="0" :dotScale="0.5"></vue-qr>
        <p>哈哈哈</p>
        <button type="button" class="shot-btn" @click="screenShot">截圖</button>
        <img id="new_img" :src="img" v-if="img"/>
      </div>
    </section>
  </div>
</template>
<script>
import HeaderCom from "@/components/header"; //頁面頭部
import {changeUrl} from "@/utils/changeUrl"
import VueQr from 'vue-qr'; //二維碼插件
import html2canvas from 'html2canvas'
export default {
  data() {
    return {
      isWeiXin: TS_WEB.isWeiXin,
      isApps: TS_WEB.isApp,
      config: {
        value: '',
        logo: require('@/statics/images/system/sjbj.jpg')
      },
      img: ""
    };
  },
  components: {
    HeaderCom,
    VueQr,
    html2canvas
  },
  methods: {
    changeUrl,
    screenShot() {
      html2canvas(this.$refs.imageToFile, {
        width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
        height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
      }).then((canvas) => {// 第一個參數是需要生成截圖的元素,第二個是自己需要配置的參數,寬高等
        this.img = canvas.toDataURL('image/png');
      })
    }
  },
  mounted(){
    this.config.value = "https://www.baidu.com/";
  },
  created() {
    document.title='html2canvas截圖'
  }
};
</script>
 
<style lang="less" scoped>
// 盒子模型
#pageDiv {
  width: 100%;
  height: 100%;
  padding-top: 0;
  padding-bottom: 0;
  overflow: hidden;
  position: relative;
  box-sizing: border-box;
  .content{
    height: 100%;
    width: 100%;
    overflow: scroll;
    overflow-x: hidden;
    .qr-code-box{
      width: 100%;
      height: 100%;
      #new_img{
        width: 100%;
        display: block;
      }
    }
  }
}
</style>

html2canvas可用的不同配置選項:http://html2canvas.hertzen.com/configuration/

結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM