uniapp使用Canvas绘制海报代码示例微信小程序下载海报画布
示例:
<template>
<view class="container">
<view>
<canvas canvas-id="myCanvas" class="canvas"></canvas>
</view>
<view>
<button @tap="downloadPoster" class="download-btn">下载海报</button>
</view>
</view>
</template>
<script>
export default {
onLoad() {
this.drawPoster();
},
methods: {
// 下载海报
downloadPoster() {
// 获取 Canvas 绘制内容的临时图片文件路径
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
success: (res) => {
// 将临时图片文件保存到相册
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
uni.showToast({
title: '保存成功',
icon: 'success'
});
},
fail: (err) => {
uni.showToast({
title: '保存失败',
icon: 'none'
});
console.error(err);
}
});
},
fail: (err) => {
console.error(err);
}
}, this);
},
// 绘制海报
drawPoster() {
// 获取 Canvas 上下文
const ctx = uni.createCanvasContext('myCanvas', this);
// 加载背景图
uni.getImageInfo({
src: 'https://img-cdn-tx.dcloud.net.cn/uni-app/logo-U.png',
success: (res) => {
ctx.drawImage(res.path, 0, 0, 400, 600);
// 加载头像图片
uni.getImageInfo({
src: 'https://img-cdn-tc.dcloud.net.cn/uploads/avatar/001/67/43/81_avatar_max.jpg?=1613651270',
success: (res) => {
ctx.drawImage(res.path, 50, 50, 80, 80);
// 绘制姓名文字
ctx.setFontSize(26);
ctx.setFillStyle('#ff0000');
ctx.fillText('Mike', 150, 100);
// 加载小程序二维码图片
uni.getImageInfo({
src: 'https://img-cdn-tc.dcloud.net.cn/uploads/avatar/000/08/81/38_avatar_max.jpg?=0',
success: (res) => {
ctx.drawImage(res.path, 50, 250, 80, 80);
// 绘制完成,保存图片
ctx.draw(false, () => {
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
success: (res) => {
console.log(res.tempFilePath);
// res.tempFilePath 就是绘制后的海报图片路径
}
}, this);
});
}
});
}
});
}
});
}
},
}
</script>
<style scoped>
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.canvas {
width: 300px;
height: 400px;
}
</style>
结束