本篇文章给大家带来的内容是关于微信小程序中生成图片的代码,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。添加画布 首先,在小程序里进行绘图操作需要用到组件,步骤大致分为以下3个部分:一张大的背景图,一段动态的文字(‘标题 用户名 及其他信息’),以及一个小程序码图片。那我们就先在我们的wxml代码中放入如下的
第三方函数引入 const util = require('../../utils/util.js') //util.js
var Promise = require('../components/bluebird.min.js')
module.exports = {
promisify: api => {
return (options,...params) => {
return new Promise((resolve,reject) => {
const extras = {
success: resolve,fail: reject
}
api({ ...options,...extras },...params)
})
}
}
} bluebird.min.js大家可自己百度下载,源文件代码太长,我这里就不复制粘贴了。 //获取手机宽高
wx.getSystemInfo({
success: function (res) {
wc.put('phoneInfo',res)
}
});
var windowHeight = phoneInfo.windowHeight,windowWidth = phoneInfo.windowWidth
self.setData({
windowHeight: windowHeight,windowWidth: windowWidth
})
//在这段代码中,我们通过使用wx.getImageInfo这个API来下载一个网络图片到本地(并可获取该图片的尺寸等其他信息),然后调用ctx.drawImage方法将图片绘制到画布上,填满画布。
const wxGetImageInfo = util.promisify(wx.getImageInfo)
//绘制二维码
Promise.all([
//背景图
wxGetImageInfo({
src: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1536213812443&di=753a0a49acfd390fba9fd7884daafa5c&imgtype=0&src=http%3A%2F%2Fi5.hexunimg.cn%2F2016-08-10%2F185422031.jpg'
}),//二维码
wxGetImageInfo({
src: 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1898297765,3486952215&fm=26&gp=0.jpg'
})
]).then(res => {
console.log(res)
if (res[0].errMsg == "getImageInfo:ok" && res[1].errMsg == "getImageInfo:ok"){
const ctx = wx.createCanvasContext('shareCanvas')
// 底图
ctx.drawImage(res[0].path,windowWidth,windowHeight)
//写入文字
ctx.setTextAlign('center') // 文字居中
ctx.setFillStyle('#f3a721') // 文字颜色:黑色
ctx.setFontSize(22) // 文字字号:22px
ctx.fillText("作者:墜夢—Eric",windowWidth / 2,windowHeight / 2)
// 小程序码
const qrImgSize = 150
ctx.drawImage(res[1].path,(windowWidth - qrImgSize) / 2,windowHeight / 1.8,qrImgSize,qrImgSize)
ctx.stroke()
ctx.draw()
}else{
wx.showToast({
title: '邀请卡绘制失败!',image:'../../asset/images/warning.png'
})
}
}) 这样,差不多我们的分享图就生成好了。 长按图片保存到系统相册要把它保存进用户的系统相册中去,实现这个功能,我们主要靠wx.canvasToTempFilePath 和wx.saveImageToPhotosAlbum 这两个API。 主要的流程就是先通过wx.canvasToTempFilePath 将 上绘制的图像生成临时文件的形式,然后再通过wx.saveImageToPhotosAlbum 进行保存到系统相册的操作。 //保存邀请卡
saveInviteCard:function(){
console.log('保存图片')
const wxCanvasToTempFilePath = util.promisify(wx.canvasToTempFilePath)
const wxSaveImageToPhotosAlbum = util.promisify(wx.saveImageToPhotosAlbum)
wxCanvasToTempFilePath({
canvasId: 'shareCanvas'
},this).then(res => {
return wxSaveImageToPhotosAlbum({
filePath: res.tempFilePath
})
}).then(res => {
wx.showToast({
title: '已保存到相册'
})
})
} (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|