使用 html2canvas 插件实现网页截图(将html保存为图片)

1.下载 html2canvas 插件

npm i -s html2canvas

2. 封装 html2Canvas.js,比如src/utils/html2Canvas.js

import html2canvas from 'html2canvas'

// 生成快照
const snapshot = (dom, options = {}) => {
  // 设置放大倍数
  const scale = window.devicePixelRatio
  // 传入的节点宽高
  const width = dom.offsetWidth
  const height = dom.offsetHeight

  // html2canvas配置项
  const opts = {
    scale,
    width,
    height,
    useCORS: true, // 使用跨域(当allowTaint为true时,此设置无效)
    allowTaint: false,
    ...options
  }

  return html2canvas(dom, opts).then(canvas => {
    // 返回图片的二进制数据
    return canvas.toDataURL('image/png', 1.0) // 将canvas转为base64格式的图片, 0-1 表示清晰度
  })
}

export default snapshot

3.在组件中使用


<template>
  <div class="wrap" >
    <div class="ct" v-if="bgImg">
      <div class="ct-submit" v-throttle="saveImg">截取图片div>
      <div class="ct-content" id="poster" ref="poster" :style="bgImg ? setStyle() : ''">
        <div class="ct-txt">{{'热门补贴一次看完,热门补贴一次看完,热门补贴一次看完'}}div>
      div>
    div>
  div>
template>

<script>
import axios from 'axios'
import snapshot from '@/utils/html2Canvas'
export default {
  data () {
    return {
      bgImg: '',
      text: '热门补贴一次看完,热门补贴一次看完,热门补贴一次看完'
    }
  },
  async mounted () {
    const bgImg = await this.getImageInfo(
      '/api/Img/20211008/123456789.png'
    )
    this.bgImg = bgImg.src
  },
  methods: {
    setStyle () {
      return `background: url(${this.bgImg}) no-repeat; background-size: 100% 100%; `
    },
    // 将网络图片转换为本地图片,解决因跨域导致画布无法转换为图片问题
    getImageInfo (path) {
      return new Promise((resolve, reject) => {
        axios
          .get(path, { responseType: 'blob' })
          .then(res => {
            const blob = res.data
            const url = URL.createObjectURL(blob)
            const img = new Image()
            img.src = url
            img.onload = () => {
              resolve(img)
            }
          })
          .catch(() => {
            console.log('加载图片失败')
            reject(new Error('加载图片失败'))
          })
      })
    },
    // 截取图片
    async saveImg () {
	  const imgBase64 = await snapshot(this.$refs.poster)
      console.log(`imgBase64`, imgBase64) // data:image/png;base64, ....
    }
  }
}
script>

踩坑记:
1.css 省略号无效

	// css省略号的方式,html2Canvas截图时无法获取文本内容
    .ct-txt {
	    display: -webkit-box;
	    -webkit-box-orient: vertical;
	    -webkit-line-clamp: 2;
	    overflow: hidden;
  }

你可能感兴趣的:(vue实战,html,javascript,vue)