附代码
html
<canvas canvas-id="firstCanvas" style="width:{{screen_width*375+'px'}}; height:{{screen_width*375*2.1666667+'px'}}" bindtap='preImg'></canvas>
data: {
screen_width:'',//屏幕宽度占比
tempFilePath:'',//图片零时地址
phoneSystemInfo:''//手机系统信息
},
onLoad: function () {
const _this = this
wx.getSystemInfo({
success: function (res) {
console.log(res)
_this.setData({
phoneSystemInfo:res,
screen_width: res.windowWidth / 375,
})
}
})
this.drawPoster()
},
drawPoster() {
let ctx = wx.createCanvasContext('firstCanvas'), that = this.data,_this = this;
let rpx = that.screen_width
let windowWidth = rpx * 375;
let windowHeight = windowWidth * 2.1666667
//这里的rpx是相对不同屏幕宽度的相对单位,实际的宽度测量,就是实际测出的px像素值*rpx就可以了;之后无论实在iPhone5,iPhone6,iPhone7...都可以进行自适应。
ctx.setFillStyle('#1A1A1A')
ctx.fillRect(0, 0, rpx * 375, windowHeight)
ctx.fillStyle = "#FFFFFF";
ctx.setFontSize(16 * rpx)
ctx.setTextAlign('center')
ctx.fillText('以下文字以屏幕中轴线为校验', windowWidth / 2, 40 * rpx)
ctx.setFontSize(24 * rpx)
ctx.fillStyle = "#E8CDAA";
ctx.setTextAlign('left')
ctx.fillText('textAlign=center', windowWidth / 2, 80 * rpx)
ctx.setTextAlign('right')
ctx.fillText('textAlign=center', windowWidth / 2, 120 * rpx)
ctx.setTextAlign('center')
ctx.fillText('textAlign=center', windowWidth / 2, 160 * rpx)
ctx.setTextAlign('left')
ctx.setFontSize(16 * rpx)
ctx.save();
ctx.draw(false, () => {
console.log('画完了')
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: rpx * 375,
height: rpx * 375*2.1666667,
canvasId: 'firstCanvas',
fileType: 'jpg',
success: function (res) {
_this.setData({
tempFilePath: res.tempFilePath
})
console.log(res.tempFilePath);
//自动保存模式
// wx.saveImageToPhotosAlbum({
// filePath: res.tempFilePath,
// success: (res) => {
// console.log(res)
// },
// fail: (err) => { }
// })
}
})
})
},
preImg:function(){//用户点击canvas预览可以保存或者转发
console.log('预览图片')
let _this = this
wx.previewImage({
current: _this.data.tempFilePath, // 当前显示图片的http链接
urls: [_this.data.tempFilePath] // 需要预览的图片http链接列表
})
}分为两种情景
情景一:
用户点击canvas进入图片预览,可以直接长按图片弹出按钮可选择直接发送给好友

情景二
直接触发保存图片到本地,用户可进入聊天页面选择图片进行发送

