uniapp 使用html2canvas将指定dom内容写入Canvas生成图片并下载

uniapp 使用html2canvas将指定dom内容写入Canvas生成图片并下载
注:
1、下载图片但是只支持app
2、可以切换背景图
3、图片和html2canvas.min.js,请自行更换

<template>
    <view class="createIDcard">
        <view class="contid">

            <view class="idPositive pubtml renderjs" :change:msg="renderScript.idPositive"  id="idPositive" :style="[{backgroundImage:'url('+tmpImg+')'},{color:tmpColor}]">
                <image src="../../../static/images/login/login.png" mode="" class="attra"></image>
                <view class="pertsInfo">
                    <view>名字</view>
                    <view>性别</view>
                    <view>性格</view>
                    <view>身份证号:CW202010101099</view>
                </view>
            </view>
            <view class="idBack pubtml" id="idBack" :change:msg="renderScript.idPositive"  :style="[{backgroundImage:'url('+tmpImg+')'},{color:tmpColor}]">
                <view class="idBackTitle">身份卡</view>
                <view class="idBackIssued ">发证机关:江苏</view>
                <view class="idBackValidity">有效期:2021-03-05-永久</view>
            </view>
            <view class="poster-view">
                <image :src="base64" mode=""></image>
            </view>
            <view class="switchTemplate">
                <view class="tmpTitle">更换模板</view>
                <view class="tmpLKist">
                    <image :src="item.url" mode="" v-for="(item,index) in tmpKist" :key='index' @click="selectTmpl(item)"></image>
                    <!-- 	<image src="../../../static/images/bronze.jpg" mode=""></image>
					<image src="../../../static/images/diamonds.jpg" mode=""></image>
					<image src="../../../static/images/writeOffBg.jpg" mode=""></image>
					<image src="../../../static/images/value.jpg" mode=""></image> -->
                </view>
            </view>
        </view>
        <view class="idCardBtn">
            <view class="saveIdcard" @click="renderScript.html2can">保存图片</view>
            <view class="saveIdcard shared">我要分享</view>
        </view>
    </view>
</template>
<script>
    export default {
        components: {},
        name: "createIDcard",
        data() {
            return {
                base64: '',
                base641: '',
                tmpImg: '',
                tmpColor: '',
                tmpKist: [{
                        url: '../../../static/images/gold.jpg',
                        color: '#fff',
                    },
                    {
                        url: '../../../static/images/bronze.jpg',
                        color: '#f66',
                    },
                    {
                        url: '../../../static/images/diamonds.jpg',
                        color: '#f33',
                    },
                    {
                        url: '../../../static/images/writeOffBg.jpg',
                        color: 'blue',
                    },
                    {
                        url: '../../../static/images/writeOffBg.jpg',
                        color: 'yellow',
                    },

                    {
                        url: '../../../static/images/value.jpg',
                        color: '#000',
                    },
                ]
            };
        },
        onLoad(options) {

            this.tmpImg = this.tmpKist[0].url;
            this.tmpColor = this.tmpKist[0].color;
        },
        methods: {
            selectTmpl(item) {
                this.tmpImg = item.url;
                this.tmpColor = item.color;
            },
            // 接收renderjs发回的数据
            receiveRenderData(val) {
                this.base64 = val
                console.log(val.length)
            },
          
            // 保存图片
            saveHeadImgFile(base64) {
                this.base64 = base64
                // #ifdef H5
                
                // #endif
                // #ifdef APP-PLUS
                    const bitmap = new plus.nativeObj.Bitmap("test");
                    bitmap.loadBase64Data(base64, function() {
                        const url = "_doc/" + new Date().getTime() + ".png"; // url为时间戳命名方式
                        console.log('saveHeadImgFile', url)
                        bitmap.save(url, {
                            overwrite: true, // 是否覆盖
                            // quality: 'quality'  // 图片清晰度
                        }, (i) => {
                            uni.saveImageToPhotosAlbum({
                                filePath: url,
                                success: function() {
                                    uni.showToast({
                                        title: '图片保存成功',
                                        icon: 'none'
                                    })
                                    bitmap.clear()
                                }
                            });
                        }, (e) => {
                            uni.showToast({
                                title: '图片保存失败',
                                icon: 'none'
                            })
                            bitmap.clear()
                        });
                    }, (e) => {
                        uni.showToast({
                            title: '图片保存失败',
                            icon: 'none'
                        })
                        bitmap.clear()
                    });
                // #endif
            }
        },
    }
</script>

<script module="renderScript" lang="renderjs">
	import html2canvas from '../../../utils/html2canvas.min.js';
	export default {
		data() {
			return {

			}
		},
		mounted() {},
		methods: {
            html2can(e, ownerVm,callBack) {
                this.emitData(e, ownerVm,1, (url) => {
                   ownerVm.callMethod('saveHeadImgFile', url)
                    this.emitData(e, ownerVm,2, (url) => {
                        ownerVm.callMethod('saveHeadImgFile', url)
                    })
                })
            },
			// 渲染到canvas并转图片
			emitData(e, ownerVm,index, callBack) {
                var dom;
                if (index == 1) {
                    dom = document.getElementById('idPositive')
                } else if (index == 2) {
                    dom = document.getElementById('idBack')
                }
				html2canvas(dom, {
					width: dom.clientWidth, //dom 原始宽度
					height: dom.clientHeight,
					scrollY: 0, // html2canvas默认绘制视图内的页面,需要把scrollY,scrollX设置为0
					scrollX: 0,
					useCORS: true, //支持跨域,但好像没什么用
				}).then((canvas) => {
					// 将生产的canvas转为base64图片3
                     let base64 = canvas.toDataURL('image/png')
                     callBack && callBack(base64)
				});
			}
		}
	};
</script>
<style lang="less" scoped>
    .createIDcard {
        width: 100%;
        overflow: hidden;

        .poster-view {
            background: #007AFF;
            width: 614rpx;
            height: 332rpx;

            image {
                width: 100%;
                height: 100%;
            }
        }

        .idCardBtn {
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            position: fixed;
            left: 0;
            bottom: 40rpx;
            z-index: 999s;

            .saveIdcard {
                width: 305rpx;
                height: 94rpx;
                background: #FFFFFF;
                box-shadow: 0px 14rpx 24rpx 0rpx rgba(214, 214, 214, 0.31);
                border-radius: 32rpx;
                border: 2px solid #DC5F45;
                line-height: 94rpx;
                text-align: center;
                font-size: 36rpx;
                font-weight: 400;
                color: #DC5F45;
            }

            .shared {
                background: #DC5F45;
                box-shadow: 0px 14rpx 24rpx 0px rgba(220, 95, 69, 0.31);
                margin-left: 24rpx;
                color: #FFFFFF;
            }
        }

        .tmpLKist {
            width: 100%;
            overflow-y: hidden;
            overflow-x: auto;
            height: 132rpx;
            white-space: nowrap;

            &::-webkit-scrollbar {
                display: none
            }

            image {
                width: 192rpx;
                height: 132rpx;
                border-radius: 6rpx;
                margin-left: 19rpx;
            }
        }

        .switchTemplate {
            width: 100%;
            color: #000;
            font-weight: 500;
            font-size: 34rpx;
            overflow: hidden;

            .tmpTitle {
                margin-bottom: 32rpx;
            }
        }

        .contid {
            width: calc(100% - 96rpx);
            margin: 48rpx 48rpx 0 48rpx;
            padding: 20rpx;
            background-color: #fff;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
        }

        .pubtml {
            width: 614rpx;
            height: 332rpx;
            border-radius: 14rpx;
            display: flex;
            margin-bottom: 32rpx;
            background-repeat: no-repeat;
            background-size: 100% 100%;
        }

        .idPositive {
            justify-content: flex-start;
            align-items: flex-start;

            .attra {
                width: 80rpx;
                height: 80rpx;
                border-radius: 50%;
                margin: 48rpx 18rpx 0 32rpx;
            }

            .pertsInfo {
                font-size: 30rpx;
                font-weight: 400;
                // color: #FFFFFF;
                margin-bottom: 10rpx;
                margin-top: 48rpx;
            }
        }

        .idBack {
            justify-content: center;
            align-items: center;
            flex-direction: column;
            font-size: 28rpx;
            font-weight: 400;
            // color: rgba(255, 255, 255, 0.85);

            .idBackTitle {
                font-size: 38rpx;
                font-weight: 500;
                // color: #FFFFFF;
                margin: 77rpx 0 70rpx 0;
            }
        }
    }
</style>

uni-app使用html2canvas生成图片的步骤如下: 1. 首先,在你的uni-app项目中安装html2canvas插件。可以使用以下命令进行安装: ```shell npm install html2canvas ``` 2. 在你的代码中引入html2canvas,并编写生成图片的方法。可以参考以下代码: ```javascript <script lang="renderjs" module="canvasImage"> import html2canvas from 'html2canvas' export default { methods: { generateImage(e, ownerFun) { ownerFun.callMethod('_showLoading', '正在生成图片') setTimeout(() => { const dom = document.getElementById('pagePoster') html2canvas(dom, { width: dom.clientWidth, height: dom.clientHeight, scrollY: 0, scrollX: 0, useCORS: true, }).then((canvas) => { ownerFun.callMethod('receiveRenderData', canvas.toDataURL('image/png')) }).catch(err => { ownerFun.callMethod('_errAlert', `【生成图片失败,请重试】${err}`) }) }, 300) } } } </script> ``` 在上面的代码中,我们通过调用`html2canvas`函数来生成图片。需要传入一个DOM节点作为参数,这里使用`document.getElementById('pagePoster')`来获取需要生成图片的节点。生成成功后,可以通过`canvas.toDataURL('image/png')`获取图片的base64位的URL。 3. 在需要生成图片的地方调用`generateImage`方法。可以参考以下代码: ```html <button @click="generateImage">生成图片</button> ``` 在上面的例子中,我们将生成图片的方法绑定在按钮的点击事件上。 通过以上步骤,你就可以在uni-app使用html2canvas生成图片了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [小程序 uniapp中webview内嵌H5页面 html2canvas截图 base64的图片保存到手机相册](https://blog.csdn.net/M__O__M/article/details/126985611)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [uni-app使用 html2canvas 生成图片(支持多端)](https://blog.csdn.net/weixin_42779803/article/details/118384426)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

给钱,谢谢!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值