html2canvas.vue 2.37 KB
<template>
  <div>
    <!-- 生成图片后隐藏原始结构 -->
    <div v-if="flag" ref="canvasRef" style="width: 200px; height: 200px;">
      <img :src="logo_image" alt="" />
    </div>
    <div v-if="imgUrl">
      <img :src="imgUrl" alt="" crossOrigin="anonymous"  style="width: 300px; height: 300px;"/>
    </div>
    <div>
      <div @click="createImage">合成图片</div>
    </div>
  </div>
</template>

<script setup>

import logo_image from '@images/logo@3x.png'
</script>

<script>
import mixin from 'common/mixin';
import html2canvas from "html2canvas";

export default {
  mixins: [mixin.init],
  data() {
    return {
      imgUrl: "",
      flag: true
    }
  },
  mounted() {

  },
  methods: {
    createImage() {
      this.$nextTick(() => {
        // 获取要生成图片的 DOM 元素
        let canvasDom = this.$refs.canvasRef;
        const options = {
          // backgroundColor: '#ffffff',
          // canvas: canvas,
          useCORS: true,//配置允许跨域
          // scale:1,
          // windowWidth: document.body.scrollWidth,
          // windowHeight: document.body.scrollHeight,
          // x: 0,
          // y: window.pageYOffset,
          // allowTaint: true,
          // background: "#ffffff", // 一定要添加背景颜色,否则出来的图片,背景全部都是透明的
          dpi: 300 // 处理模糊问题
        };
        // console.log("获取指定的宽高", width, height, canvas);
        html2canvas(canvasDom, options)
          .then(canvas => {
            try {
              // 生成图片地址
              this.imgUrl = canvas.toDataURL("image/png");
              // console.log("canvas.toDataURL('image/png')", this.imgUrl);
              this.flag = false;
            } catch (e) {
              alert("图片跨域,保存失败");
            }
          })
          .catch(err => {
            console.log("绘制失败");
          });
      });
    }
  }
}
</script>

<style lang="less" scoped>
.m-html2canvas {
  display: flex;
}

.m-canvasRef {
  width: 500px;
  height: 500px;
  /* border: 1px solid red; */
  /* box-sizing: border-box; */
  box-shadow: 10px 10px 5px #888888;
}

.m-imageList {
  width: 500px;
  height: calc(500px / 3);
}

img {
  width: 100%;
  height: 100%;
  float: left;
}

.m-showImage {
  margin-left: 50px;
  background: red;
  width: 500px;
  height: 500px;
}

.m-btn {
  margin-left: 50px;
}
</style>