Vue通过html2canvas实现页面生成图片

2019-12-23  本文已影响0人  二营长家的张大炮

安装html2canvas

npm install --save html2canvas

在页面中引入

<template>
  <div class="hello" id="hello" ref="hello">
    <button @click="getImageShot">截屏</button>
    <img :src="imgUrl" alt="">
    <exportExcelDialog></exportExcelDialog>
    <h1>{{ userName }}</h1>
    <button @click="setUserName('2222222')">CLick me add</button>
    <Tinymce></Tinymce>
    <img
      style="width:100px;height:100px"
      src="http://test.download.cycore.cn/zhkt/2019/10/7/3/32/4c8b0300-f178-4d7a-9b6f-a78d432be4f5.jpg"
      alt
      @click="()=>{show=true}"
    />
    <ImageBigger :show="show" :imgUrl="imgUrl" @img_close="()=>{show=false}"></ImageBigger>
    <div id="testimg"></div>
  </div>
</template>

<script>
import store from "../store/index";
import { mapState, mapActions, mapGetters, mapMutations } from "vuex";
import Tinymce from "./tinymce/index";
import exportExcelDialog from "./ExcelHandler";
// 引入图片放大组件
import ImageBigger from "../components/ImageBigger.vue";
// 引入html2canvas
import html2canvas from "html2canvas";
import axios from "axios";
export default {
  name: "HelloWorld",
  store,
  components: {
    Tinymce,
    exportExcelDialog,
    ImageBigger
  },
  data() {
    return {
      show: false,
      imgUrl:
        "http://test.download.cycore.cn/zhkt/2019/10/7/3/32/4c8b0300-f178-4d7a-9b6f-a78d432be4f5.jpg"
    };
  },
  // 获取store中的count
  computed: mapGetters(["userName"]),
  // 获取store中操作count的函数
  methods: {
    ...mapActions(["setUserName"]),
    getImageShot() {
      html2canvas(
        document.getElementById("hello"),
        {
          backgroundColor: null // null 表示设置背景为透明色
        }
      ).then(canvas => {
        let img = new Image();
        const imgUrl = canvas.toDataURL("image/jpeg");
        img.src = imgUrl;
        document.getElementById("testimg").appendChild(img);
        let a = document.createElement('a');
        a.href=imgUrl;
        a.download = "testimg";
        a.click();
      });
    }
  },
  created() {}
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}

#testimg img {
  width: 800px;
  height: 200px;
}
</style>

点击截图按钮后生成图片并下载到本地,但是打开图片之后发现,页面中原有的图片截图之后显示为空白:

image.png

原因是图片为跨域图片。

官方文档上有个配置项:


image.png

一放到服务器上面就好了,这样就不存在什么跨域问题了

上一篇下一篇

猜你喜欢

热点阅读