小程序生成图片并保存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

shareFirend(){
var _that = this;
let ctx = wx.createCanvasContext('shareCanvas');
let windowWidth = _that.data.windowWidth
let windowHeight = _that.data.windowHeight
let bgPath = '../../images/projectstate/bg.png'
_that.setData({
scale: 1.6,
canvasLeft : parseInt( (_that.data.shareViewWidth - _that.data.windowWidth )/2)
})
//绘制背景图片
ctx.drawImage(bgPath, 0, 0, windowWidth, _that.data.scale * windowWidth)
//绘制title
var titleStr = _that.data.title
var str = ""
for (var i = 0; i < titleStr.length ;i++){
if ( i%15 == 0 && i != 0){
str += '\n'+titleStr[i]
}else{
str += titleStr[i]
}
}
ctx.setFillStyle('#333333')
ctx.setFontSize(16);

var titleStrArr = str.split("\n");
titleStrArr.forEach(function(val,i,arr){
ctx.fillText(val,12, 24+i*24)
})
//绘制内容
ctx.setFillStyle('#999999')
ctx.setFontSize(11);
ctx.fillText(_that.data.nickName +" "+ _that.data.createDate, 12, titleStrArr.length*24+20);
//内容
function matchReg(str) {
let reg = /<\/?.+?\/?>/g;
console.log()
var a = str.replace(reg, '')
a.replace(new RegExp('&nbsp;', "g"))
return a.replace(new RegExp('&nbsp;', "g"), '')

}
var lastHeight = parseInt(windowHeight - ((0.36 * windowWidth) + (titleStrArr.length * 24 + 5)));
var titleHeight = parseInt(titleStrArr.length * 24 + 40);
var con = matchReg(_that.data.newsContent);
var conStr = "";
for (var i = 0; i < con.length; i++) {
if (i % 21 == 0 && i != 0) {
conStr += '\n' + con[i]
} else {
conStr += con[i]
}
}
var conStrArr = conStr.split("\n");
ctx.setFillStyle('#333333')
ctx.setFontSize(11);
conStrArr.forEach(function(val,i,arr){
if (i >= (parseInt(lastHeight / 11) -7)){
return
}else{
ctx.fillText(val, 12, titleHeight + i * 15);
}
})
//长按扫码阅读
ctx.setFillStyle('#333333')
ctx.setFontSize(13);
ctx.fillText("长按扫码阅读", 12, windowWidth*1.1);
//绘制二维码
ctx.drawImage(_that.data.imgSrc, 0.8 * windowWidth / 1.3, windowWidth*0.89, 0.36 * windowWidth, 0.36 * windowWidth)
ctx.draw();
},

savePic: function (e) {
var _that =this;
wx.canvasToTempFilePath({
canvasId: 'shareCanvas',
success: function (res) {
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(result) {
_that.setData({
shareView: 'none'
})
wx.showToast({
title: '图片保存成功',
icon: 'success',
duration: 2000
})
}
})
}
})
}

本文标题:小程序生成图片并保存

文章作者:dustlee

发布时间:2018年12月16日 - 15:10:59

最后更新:2019年08月20日 - 09:16:20

原始链接:http://www.dustlee.com/2018/12/16/小程序生成图片并保存/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。