mpaas小程序中采用html2canvas实现html转canvas保存图片
使用uniapp将代码打包一份h5部署到服务器

h5要保存的图片组件页面report.vue

安装 npm install --save html2canvas 或 yarn add html2canvas

引入import html2canvas from ‘html2canvas’;
ts


function getCanvas() {
  timeOutEvent = 0;
  uni.showModal({
    title: '提示',
    content: '您要保存图片到相册吗?',
    success(res) {
      if (res.cancel) {
        return;
      }
      // '#businessReport‘ 当前要保存为图片的代码块的id
      const id = document.querySelector('#businessReport') as HTMLElement;  // ts标注类型
   
      html2canvas(id, {
        useCORS: true,
        allowTaint: true,
        windowHeight: id.scrollHeight, // 如果图片过长,可能会出现图片保存部分空白,scrollHeight是包含滚动条的高度
         // scale和dpi可以调节图片清晰度, 选项{dpi:96}等价于{scale:1},并且任何选项的更大值都将提高分辨率。如果存在两个选项,scale则忽略使用dpi的比例。
        scale: 1,   
      }).then((canvas: any) => {	
        const dataURL = canvas.toDataURL('image/jpeg', 0.8); 、//  第二个参数可以调节图片清晰度
        function dataURLtoFile(dataurl: string, filename: string): File {
          // 获取到base64编码
          const arr = dataurl.split(',');
          const mime = arr[0].match(/:(.*?);/)[1];
          // 将base64编码转为字符串
          const bstr = window.atob(arr[1]);
          let n = bstr.length;
          const u8arr = new Uint8Array(n); // 创建初始化为0的,包含length个元素的无符号整型数组
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          return new File([u8arr], filename, {
            type: mime,
          });
        }
        const body = new FormData();
        body.append('file', dataURLtoFile(dataURL, '666.jpg'));
        // 上传图片 获取网络图片地址
        fetch(`${appCache.$jConfig.baseUrl}/new/api/api/upload?fileType=1&note=666`, {
          method: 'post',
          headers: {
            Authorization: `Bearer ${getApp().globalData!.token}`,
          },
          body,
        }).then(async function (response) {
          const { status } = response;
          let json;
          if (status === 200) {
            json = await response.json();
            try {
              if (my) {
               // 和小程序通信 触发保存图片   若是h5可以直接调用保存的方法
                my.postMessage({
                  type: 'saveImgae',
                  url: json.data,
                });
              }
            } catch (e) {
              console.log(e);
            }
          }
        });
      });
    },
  });
}

小程序中采用webview跳转到h5页面

<template class="">
  <web-view :src="url" @message="onMessage"></web-view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';
import appCache from '@/lib/appCache';
const url = ref('');
onLoad((e) => {
  url.value = `${appCache.$jConfig.baseUrl}/pages/report?userId=${e.userId}&token=${e.token}`;
});
function onMessage(e: any) {
// 接收h5传过来的参数
  if (e.detail.type === 'saveImgae') {
    // 保存图片
    uni.getImageInfo({
      src: e.detail.url,
      success: (res) => {
        my.saveImage({
          url: res.path,
          success: () => {
            my.alert({
              content: '保存成功',
            });
          },
          fail: () => {
            my.alert({
              content: '保存失败,请修改读写手机存储权限后重试',
            });
          },
        });
      },
    });
  }
}
</script>

<style scoped></style>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐