最近遇到个需求,需要根据一个指定的页面,生成图片并且进行保存,大致就是需要在canvas上画出来和当前页面一样内容,然后转存为图片这样。
准备工作 先获取到canvas对象
const query = wx.createSelectorQuery()
query.select('#myCanvas')
.fields({
node: true,
size: true
})
.exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
const dpr = wx.getSystemInfoSync().pixelRatio;
canvas.width = 640 * dpr
canvas.height = 865 * dpr
ctx.scale(dpr, dpr)
})
绘制文字
ctx.save()
ctx.font = 'normal normal 26px SourceHanSerifCN';
ctx.fillStyle = '#928e93';
ctx.fillText("绘制的文字内容", 88, 790);
ctx.restore();
绘制自动换行的文字
let tempText = "我是需要换行的文字\n我的内容很长很长很长很长很长"
let textList = tempText.split("\n")
let bookLength = 12
let bookSize = 36
let bookLine = 48
if(tempText.length>=50){
bookLength = 13
bookSize = 34
bookLine = 46
}
if(tempText.length>=90){
bookLength = 15
bookSize = 30
bookLine = 40
}
if(tempText.length>=150){
bookLength = 17
bookSize = 26
bookLine = 36
}
for (let i = 0; i < textList.length; i++) {
let item = textList[i]
let MaxLength = 0
let MaxIndex = 0
let tempItem = item.split("")
tempItem.forEach((items,index)=>{
if (items.match(/[^\x00-\xff]/ig) != null){
MaxLength+=2
}else{
MaxLength+=1
}
if(MaxLength<=bookLength*2){
MaxIndex = index
}
})
if (MaxLength > bookLength*2) {
textList[i] = item.substring(0, MaxIndex);
textList.splice(i + 1, 0, item.substring(MaxIndex, item.length))
}
}
ctx.save()
ctx.font = "normal " + bookSize + "px 'SourceHanSerifCN'";
ctx.fillStyle = '#413e44';
let booksTop = 180
if (textList.length >= 4) {
booksTop = 114
}
if (textList.length >= 6) {
booksTop = 104
}
textList.forEach((item, index) => {
ctx.fillText(item, 86, (booksTop + index * bookLine));
})
ctx.restore();
绘制矩形
ctx.save()
ctx.fillStyle = '#f0f1f1'
ctx.fillRect(435, 685, 124, 124)
ctx.restore();
绘制图片
const bg = canvas.createImage();
bg.src = "../../static/image/xxxx.png"
bg.onload = function () {
ctx.drawImage(bg, 0, 0, 640, 865);
}
绘制用户头像(头像绘制需要先画个圆,然后在圆左上角位置开始绘制头像,画圆的时候是圆的中心点开始画的)
const avatar = canvas.createImage();
let avatorSrc = "我是头像地址"
avatar.src = avatorSrc
avatar.onload = function () {
ctx.save()
ctx.arc(117, 589, 29, 0, 2 * Math.PI)
ctx.clip()
ctx.drawImage(avatar, 88, 560, 58, 58)
ctx.restore();
}
最好差不多了,就可以生成图片,并且对图片进行保存了
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 640,
height: 865,
destWidth: 640 * 4,
destHeight: 865 * 4,
canvas: canvas,
fileType: 'png',
quality: 100,
success: function (res) {
console.log("保存图片到相册", res);
wx.saveImageToPhotosAlbum({ //保存图片到相册
filePath: res.tempFilePath,
success: function () {
wx.hideLoading()
wx.showToast({
title: "保存图片成功!",
duration: 2000
})
},
fail() {
wx.showToast({
title: "保存失败!",
icon: 'none',
duration: 2000
})
wx.hideLoading()
}
})
},
fail(e) {
wx.hideLoading()
console.log("失败", e)
}
})