最近开发生成并分享海报的功能时,想参考一下网上做法,但是搜索了一下网上调用的大多数是低版本的Canvas官方接口,而且在开发的过程也遇到了真机图片不显示、真机字体模糊的问题,所以自己整理一个新接口样例,提供大家参考下,具体代码如下:
// wxml代码
<view class="card" style="width: {{width}}px;">
<canvas type="2d" id="shareCard" style="width: {{width}}px;height: 450px;"></canvas>
</view>
复制代码
// js代码
data: {
width: 0,
height: 0,
pixelRatio: null,
canvasObj: null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var _this = this
wx.getSystemInfo({
success: function(res) {
_this.setData({
pixelRatio: res.pixelRatio, // 设备像素比
width: res.windowWidth - 40 // 设置canvas宽度
})
},
})
_this.createdPoster();
},
/**
* 生成海报
*/
createdPoster() {
var _this = this;
const query = wx.createSelectorQuery()
query.select('#shareCard')
.fields({ node: true, size: true })
.exec((res) => {
var width = res[0].width
var height = res[0].height
const canvas = res[0].node
const ctx = canvas.getContext('2d')
_this.setData({
canvasObj: canvas,
height: canvas.height
})
canvas.width = width * _this.data.pixelRatio
canvas.height = height * _this.data.pixelRatio
ctx.scale(_this.data.pixelRatio, _this.data.pixelRatio)
// 绘制图片背景
const backImg = canvas.createImage();
backImg.src = '/images/base-info.jpg';//微信请求返回头像
backImg.onload = () => {
// 绘制名字
ctx.drawImage(backImg, 0, 0, canvas.width, 250);
ctx.font = 'normal bold 18px sans-serif';
ctx.fillStyle = '#ffffff'
ctx.fillText('生成海报', 30, 50);
ctx.draw = true;
}
// 绘制二维码
const codeImg = canvas.createImage();
codeImg.src = '/images/qr-code.jpg';//微信请求返回头像
codeImg.onload = () => {
var left = width / 2 - 70
ctx.drawImage(codeImg, left, 280, 140, 140);
}
// 设置背景
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, canvas.width, canvas.height)
})
},
/**
* 保存海报信息
*/
saveCodeImg() {
var _this = this
wx.canvasToTempFilePath({
x: 0,
y: 0,
canvas: _this.data.canvasObj,
success: function(res) {
console.log(res)
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
console.log('res', res);
wx.showToast({
title: '已保存到相册',
icon: 'success',
duration: 3000
})
}
})
},
fail: function(res) {
console.log(res);
}
});
}
复制代码
上述就是生成海报的简单样例,在整个过程中,有两个点需要注意的:
一是:引入本地图片,直接引入的话会报错,需按照如下格式引入
// 绘制图片背景
const backImg = canvas.createImage();
backImg.src = '/images/base-info.jpg'; // 微信请求返回头像
backImg.onload = () => {
// 设置背景图片
ctx.drawImage(backImg, 0, 0, canvas.width, 250);
}
复制代码
二是:当我们真机运行时,会发现字体和图片会变得特别的模糊,需按照如下格式设置
// 将canvas按照像素比倍数放大
canvas.width = width * _this.data.pixelRatio
canvas.height = height * _this.data.pixelRatio
ctx.scale(_this.data.pixelRatio, _this.data.pixelRatio)
复制代码