美文网首页
uniapp中使用html2canvas做H5端的海报生成功能

uniapp中使用html2canvas做H5端的海报生成功能

作者: 周星星的学习笔记 | 来源:发表于2022-06-27 22:54 被阅读0次

这两天在做一个投票分享页的功能,产品上需要做一个生成海报的功能,说白了就是将一个弹窗页生成一张图片,供用户保存下载并且分享。原先找了好多插件,uniapp插件市场上一大堆,各种使用canvas绘制出一个海报的插件,层出不穷,感觉都挺复杂的,用起来也不是很方便,后来就想到了,能不能有一个工具,能把html转换为canvas呢,于是就找到了html2canvas这个包,发现相当好用。下面就简单记录一下使用html2canvas如果做海报的。效果如下:

示例

一、安装html2canvas

npm install html2canvas --save

二、代码示例

<template>
  <view class="canvas-wrap">
    <view class="canvas-content-wrap mb20" id="poster" v-if="!imageData">
      <image :src="indexpic" class="poster-indexpic" mode="widthFix"></image>
      <view class="poster-title"> 美丽的风景 </view>
      <view class="poster-title"> 长按识别图片保存或分享给好友 </view>
      <tki-qrcode
        :val="qrcodeUrl"
        :size="248"
        :onval="true"
        :load-make="true"
      />
    </view>
    <image :src="imageData"  mode="widthFix" v-else></image>
    <button type="primary" @click="createPoster" class="mb20">生成海报</button>
  </view>
</template>

<script>
//html转canvas
import html2canvas from 'html2canvas'
//导入二维码组件
import tkiQrcode from '@/components/tki-qrcode/tki-qrcode'

export default {
  components: {
    tkiQrcode
  },
  data() {
    return {
      //海报封面
      indexpic: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fww3.sinaimg.cn%2Fmw690%2F7861449bly1h3j4ranhgyj20m80cijs0.jpg&refer=http%3A%2F%2Fwww.sina.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1658933309&t=b7ddddc666de4ec4d28129ebb3ce01de',
      //最后生成的图片信息
      imageData: null
    }
  },
  computed: {
    //二维码链接
    qrcodeUrl() {
      //测试链接
      return 'http://m.xxxx.com'
    }
  },
  methods: {
    //生成海报
    createPoster() {
      uni.showLoading({
        title: '正在生成海报'
      })
      let dom = document.querySelector('#poster')
      html2canvas(dom, {
        width: dom.clientWidth, //dom 原始宽度
        height: dom.clientHeight,
        scrollY: 0,
        scrollX: 0,
        useCORS: true
      }).then((canvas) => {
        uni.hideLoading()
        //成功后调用返回canvas.toDataURL返回图片的imageData
        this.imageData = canvas.toDataURL('image/png', 1)
      })
    },
  }
}
</script>

<style lang="scss">
.canvas-wrap {
  padding: 40rpx;
  text-align: center;
  .canvas-content-wrap {
    background: rgb(224, 187, 63);
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #ffffff;
    padding: 20rpx;
    z-index: -1;
    .poster-indexpic {
      height: 200rpx;
      margin-bottom: 40rpx;
    }
    .poster-title {
      font-size: 32rpx;
      margin-bottom: 40rpx;
    }
  }
}
</style>

三、注意事项

  • html中使用的图片链接一定要支持跨域,否则生成的海报中图片那块区域可能会是空的。
  • 微信里面点图片长按自动能唤起保存图片以及识别二维码的功能。

相关文章

网友评论

      本文标题:uniapp中使用html2canvas做H5端的海报生成功能

      本文链接:https://www.haomeiwen.com/subject/kvkovrtx.html