<template>
<view>
<canvas canvas-id="posterCanvas" style="width: 100%; height: 400px"></canvas>
<button @click="aaa">生成海报并保存</button>
</view>
</template>
<script>
export default {
onLoad() {
this.createPosterAndSave();
},
methods: {
// 生成海报
async createPosterAndSave() {
const ctx = uni.createCanvasContext('posterCanvas', this);
const systemInfo = uni.getSystemInfoSync();
const screenWidth = systemInfo.windowWidth; //获取屏幕宽度,这样不管什么机型都能铺满
// 绘制背景图
const backgroundImage = '../../static/背景.jpg'; // 替换为你的图片路径
const canvasWidth = screenWidth; // canvas的宽度 背景图的宽度
const canvasHeight = 400; // canvas的高度 背景图的高度
// 注意:这里我们直接设置背景图的宽度为canvas宽度,高度则拉伸或裁剪以适应canvas高度
ctx.drawImage(backgroundImage, 0, 0, canvasWidth, canvasHeight);
// 绘制二维码图片(放在背景图中间)
const qrcodeImage = '../../static/logo.png'; // 替换为你的二维码图片路径
const qrcodeWidth = 100; // 二维码宽度
const qrcodeHeight = 100; // 二维码高度
// 计算二维码在背景图中间的坐标
const qrcodeX = (canvasWidth - qrcodeWidth) / 2;
const qrcodeY = (canvasHeight - qrcodeHeight) / 2;
ctx.drawImage(qrcodeImage, qrcodeX, qrcodeY, qrcodeWidth, qrcodeHeight);
// 绘制完成
ctx.draw(true);
},
// 下载海报
aaa() {
uni.canvasToTempFilePath({
canvasId: 'posterCanvas',
success: (res) => {
const tempFilePath = res.tempFilePath;
// 保存图片到相册
uni.saveImageToPhotosAlbum({
filePath: tempFilePath,
success: () => {
uni.showToast({ title: '海报已保存到相册', icon: 'success' });
},
fail: (err) => {
uni.showToast({ title: '保存失败', icon: 'none' });
console.error(err);
}
});
},
fail: (err) => {
console.error(err);
}
});
}
}
};
</script>
<style>
/* 样式可以按需添加 */
</style>
如果是本地图片上面复制可以直接拿去用,如果是网络图片参考下面。
<template>
<view>
<canvas canvas-id="myCanvas" style="width: 300px; height: 300px"></canvas>
</view>
</template>
<script>
export default {
data() {
return {
imagePath: ''
};
},
methods: {
getImageInfo() {
uni.getImageInfo({
src: 'https://uapi.zheshouka.com/qrcode/qrcode-199.png',
success: (res) => {
console.log(res);
this.imagePath = res.path;
this.drawCanvas();
},
fail: (err) => {
console.log(err);
}
});
},
drawCanvas() {
const ctx = uni.createCanvasContext('myCanvas', this);
ctx.drawImage(this.imagePath, 0, 0, 300, 300);
ctx.draw();
}
},
mounted() {
this.getImageInfo();
}
};
</script>
<style>
.container {
display: flex;
flex-wrap: wrap;
}
</style>