uniapp生成canvas商品海报
之前做一个uniapp开发的微信小程序需要生成商品海报,在网上学习后完成,记录一下。
主要使用了canvas
,uniapp官网链接:canvas使用方法
自定义生成海报组件tr-xqgenrate.vue
<template>
<view>
<u-mask :z-index="90" :show="share_qrcode_flag" :zoom="true" :custom-style="{ background: 'rgba(0,0,0,.6)' }"
:duration="300">
<view class="sq_box">
<view class="tz_box qrcode_box">
<view class="icon-close-text flex-column justify-content-conter align-items-conter"
v-if="canvasToTempFilePath!=null">
<text class="text-t">长按保存海报到相册即可分享~</text>
<text class="iconfont iconshenheweitongguo slone-iconfont" @tap="Close"></text>
</view>
<view class="share_qrcode">
<canvas canvas-id="myCanvas"
style="width: 690px;height:1060px; position: fixed;top: -10000px;"></canvas>
<image @longpress="this.showSaveImgWin = true"
style="width: 100%; height: 100%;border-radius: 10rpx;" :src="canvasToTempFilePath"></image>
</view>
</view>
</view>
</u-mask>
<u-modal v-model="showSaveImgWin" content="确定要保存图片吗" @confirm="saveShareImg(canvasToTempFilePath)"
@cancel="this.showSaveImgWin = false" :show-cancel-button="true"></u-modal>
</view>
</template>
<script>
export default {
name: 'tr-xqgenrate',
data() {
return {
ratio: 1,
ctx: null, // 创建canvas对象
canvasToTempFilePath: null, // 保存最终生成的导出的图片地址
openStatus: true, // 声明一个全局变量判断是否授权保存到相册
share_qrcode_flag: false,
showSaveImgWin: false, //保存图片到相册
};
},
methods: {
Close() {
this.share_qrcode_flag = false
setTimeout(() => {
this.$emit('IsbuttomBuy', true)
}, 180)
},
share_qrcode(XqOption) {
if (!this.canvasToTempFilePath) {
this.createCanvasImage(XqOption);
} else {
this.$emit('IsbuttomBuy', false)
}
this.share_qrcode_flag = true;
},
//获取图片信息
downloadFileImg(url) {
return new Promise(resolve => {
uni.getImageInfo({
src: url,
success: res => {
resolve(res.path);
},
fail: err => {
uni.showToast({
title: '网络错误请重试',
icon: 'loading'
});
}
});
});
},
// 生成海报
async createCanvasImage(option) {
if (!this.ctx) {
uni.showLoading({
title: '正在生成海报...'
});
let code = this.downloadFileImg(option.codeUrl); //小程序太阳码
let cover = this.downloadFileImg(option.GoodsImage); //商品图片
let headImg =