uniapp实现html转换为图片并下载

在使用uniapp开发支付宝小程序时,碰到了需要将html转化为图片并下载的需求,发现在支付宝小程序中无法使用html2canvas进行处理,所以使用canvas自己绘制的方式,主要代码如下所示:

html 复制代码
<view id="container">
<!-- 需要转换的html代码 -->
</view>
<canvas id="myCanvas"></canvas>
javascript 复制代码
my.createSelectorQuery().select('#container').boundingClientRect().exec((ret) => {
    const rect = ret[0];
    //rect为container实例对象,可以获取到宽高等参数
    const context = my.createCanvasContext('myCanvas');
    //手写需要绘制的内容
    context.fillText('申请人姓名:小如', 10, 10)
    context.draw(true, () => {
        my.canvasToTempFilePath({
            canvasId: 'myCanvas',
            success: (res) => {
                console.log('图片路径:' + res.tempFilePath);
                my.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success(res) {
                        console.log(res);
                    },
                    fail(err) {
                        console.log(err);
                    },
                });
            },
            fail: (err) => {
                console.error('生成图片失败:', err);
            }
        });
    });
})

在h5页面中,可以使用html2canvas进行处理

javascript 复制代码
import html2canvas from 'html2canvas';
import { saveAs } from 'file-saver';

//调用save方法进行转换
save() {
  const container = document.querySelector('#container'); // 获取包含需要保存为图片的元素的容器
  // 使用html2canvas将元素转换为canvas
  html2canvas(container).then((canvas) => {
    let url = canvas.toDataURL('image/png');
    this.src = url;  //获取到了url可以直接在界面中展示
    // 将canvas转换为Blob对象
    // canvas.toBlob((blob) => {
    //   saveAs(blob, '考试安排.png');
    //   uni.saveImageToPhotosAlbum({
    //     filePath: blob,
    //     success() {
    //       uni.showToast({
    //         title: '保存成功',
    //         icon: 'success'
    //       });
    //     },
    //     fail() {
    //       uni.showToast({
    //         title: '保存失败',
    //         icon: 'none'
    //       });
    //     }
    //   });
    // }, 'image/png');
  });
}
相关推荐
我叫张小白。9 分钟前
Vue3 Hooks:逻辑复用的解决方案
前端·javascript·vue.js·前端框架·vue
S***t71412 分钟前
前端物联网开发
前端·物联网
我叫张小白。20 分钟前
Vue3 Props 的使用:组件间数据传递的桥梁
前端·javascript·vue.js·vue3
r***869821 分钟前
Nginx解决前端跨域问题
运维·前端·nginx
广州华水科技28 分钟前
单北斗GNSS在桥梁变形监测中的关键应用与技术优势分析
前端
IT_陈寒28 分钟前
Python 3.12新特性实战:10个让你效率翻倍的代码优化技巧
前端·人工智能·后端
z***948429 分钟前
Redis 6.2.7安装配置
前端·数据库·redis
2301_8072886331 分钟前
MPRPC项目制作(第四天)
java·服务器·前端
J***793932 分钟前
前端在移动端中的React Native Windows
前端·react native·react.js
阿雄不会写代码32 分钟前
PPTX报错AttributeError: module ‘collections‘ has no attribute ‘Container‘
前端