小程序
這個問題我上網(wǎng)搜了一下,答案有多種惠豺,但是真正能用的沒有幾何。很多答案都是雷同风宁,有的網(wǎng)友也不負責(zé)任洁墙,直接拿來照抄,自己也不跑一遍看看戒财。哎热监,不說了,說多了全是淚饮寞。希望我們的技術(shù)達人在分享的時候孝扛,能夠真實的走一遍代碼列吼,盡量能讓我等小白看的懂啊。鬧騷發(fā)過了苦始,下面我們就進入正題吧(__) 嘻嘻……
今天分享的是不僅僅把頁面生成圖片寞钥,同時,也要滿足能夠識別圖中的二維碼陌选。
canvas組件
要想把頁面生成圖片理郑,canvas是必不可少的,網(wǎng)上很多朋友說咨油,頁面生成的圖片背景是空白您炉,這個問題我遇到過,產(chǎn)生背景的原因是因為我們背景圖片不能是本地地址役电,必須是網(wǎng)絡(luò)地址赚爵,而且這個地址必須是https開頭的,否則圖片調(diào)用失敗法瑟。由于我寫的這個案例沒有涉及到網(wǎng)絡(luò)圖片冀膝,所以我這個代碼基本上沒有出現(xiàn)問題。具體操作如下瓢谢。
新建wxml頁面
<canvas canvas-id='share' style='width:375px;height:580px' hidden='{{canvasHidden}}'></canvas>
<view class='container-main'>
<view class='am-title'>點擊圖片預(yù)覽后畸写,長按或點擊右上角保存分享</view>
<view class='point-img'>
<image src='../../images/bj.png' class='bjt'></image>
<view class="point-container">
<view class="am-img"><image src='{{imgurl}}'></image></view>
<view class='am-cname'>姓名:<text>{{cname}}</text></view>
<view class='am-yuyan'>近期預(yù)言:<text>{{yuyan}}</text></view>
<view class='am-renwu'>人物匹配:<text>{{renwu}}</text></view>
<view class='am-fan'>前世煩惱:<text>{{fan}}</text></view>
<view class='am-xg'>人物性格:<text>{{xg}}</text></view>
<view class="content"><image src='../../images/11.png' class='seal'></image>
</view>
</view>
<view class='am-div'></view>
</view>
</view>
<view class='am-footer'>
<button open-type="share" data-tag="share1" id="btn_share1">轉(zhuǎn)發(fā)</button>
<button bindtap='saveImageToPhotosAlbum'>保存圖片</button>
</view>
備注:在頁面開頭我們創(chuàng)建一下 canvas組件,因為我們生成圖片是依賴它氓扛。
新建樣式(wxss)
好的頁面需要好的樣式來搭配,下面是頁面的樣式论笔,大家可以自行修改
.container-main {width:100%;}
.am-title {background-color:#96c9ca; height:70rpx;line-height:70rpx; text-align: center; color:#ffffff;
font-family: PingFangSC-Light,helvetica,'Heiti SC';font-size:.9rem;}
.point-img { width:100%;height:100%;}
.bjt {width:100%; height:85%; position: absolute; z-index: -1;}
.am-title2 {font-size:1.6rem;padding-top:20px;padding-bottom:20px;font-weight:bold; text-align: center;color:#ffffff;}
.seal {width:284px;height:80px;position: absolute;left:5%;}
.point-container {top:20vh;text-align: left;font-size:1.0rem;border-radius: 10rpx; position: absolute;
margin:10px;padding:10px;margin-top:0px;color:#5e7436;}
.am-img {text-align: center;left:35vw;}
.am-img image {width:200rpx;height:200rpx;}
.point-container text {font-weight:bold;}
.point-container .am-cname {padding-top:15rpx; padding-left:20rpx;padding-right:20rpx;}
.point-container .am-yuyan {padding-top:15rpx; padding-left:20rpx;padding-right:20rpx;}
.point-container .am-renwu {padding-top:15rpx;padding-left:20rpx;padding-right:20rpx;}
.point-container .am-fan {padding-top:15rpx;padding-left:20rpx;padding-right:20rpx;}
.point-container .am-xg {padding-top:15rpx;padding-left:20rpx;padding-right:20rpx;}
.content {margin:15rpx auto; text-align: left;}
.am-div {height:20rpx;}
.am-footer {display:flex;height: 100rpx;width: 100%; text-align: center;position: absolute;bottom:-5px;left:0;}
.am-footer button {border:#ff6a38 1px solid; border-radius:20rpx; width:300rpx;
height: 70rpx; text-align: center; line-height:70rpx;
font-size: 30rpx;background-color:#ffffff; letter-spacing:2px;color: #E97855;}
頁面JS
這是關(guān)鍵部分采郎,所有的實現(xiàn)效果就全靠它啦,具體如下:
const app = getApp();
var WxParse = require('../../wxParse/wxParse.js')
/*
小程序利用canvas實現(xiàn)一鍵保存圖片功能
https://blog.csdn.net/Charles_Tian/article/details/80910616 */
Page({
/**
* 頁面的初始數(shù)據(jù)
*/
data: {
cname: '',
renwu: '',
yuyan: '',
fan: '',
xg: '',
imgurl: '', //人物頭像
canvasHidden: true, //設(shè)置畫板的顯示與隱藏狂魔,畫板不隱藏會影響頁面正常顯示
wxappName: '頁面生成圖片', //小程序名稱
shareImgPath: '',
screenWidth: '', //設(shè)備屏幕寬度
shareImgSrc: '',
},
infoShow: function () {
var that = this;
wx.request({
url: app.globalData.api_url + 'rest/findProgram/36',
method: 'GET',
header: { 'Accept': 'application/json' },
success: function (res) {
WxParse.wxParse('article_content', 'html', res.data.errMsg.s_remark, that, 5) //獲取詳細信息 res.data.content詳細信息數(shù)據(jù)
that.setData({
info: res.data.errMsg
// article_content: WxParse.wxParse('article_content', 'html', res.data.errMsg.n_remark, that, 5) //獲取詳細信息 res.data.content詳細信息數(shù)據(jù)
})
wx.setStorageSync('cmsinfo', res.data.errMsg)
},
//接口調(diào)用失敗的回調(diào)函數(shù)
fail: function (res) {
var newData = wx.getStorageInfoSync('cmsinfo')
if (newData) {
obj.setData({ info: newData })
}
that.setData({ toastHidden: false, msg: '當(dāng)前網(wǎng)格異常,請稍后再試' })
},
//口調(diào)用結(jié)束的回調(diào)函數(shù)(調(diào)用成功最楷、失敗都會執(zhí)行)
complete: function () {
//顯示出加載中的提示
that.setData({ loadHidden: true })
}
})
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面加載
*/
onLoad: function (options) {
this.infoShow();
var that = this;
wx.getImageInfo({
src: '../../images/bj.png',
success: function (res) {
console.log(res)
that.setData({
shareImgSrc: '../../' + res.path
});
}
})
wx.getImageInfo({
src: '../../images/11.png',
success: function (res) {
console.log(res)
that.setData({
shareImgPath: '../../' + res.path
});
}
})
//獲取用戶設(shè)備信息整份,屏幕寬度
wx.getSystemInfo({
success: res => {
that.setData({
screenWidth: res.screenWidth
})
console.log(that.data.screenWidth)
}
})
that.setData({
cname: options.id
});
var yuyan = new Array('多注意外表,近期將有桃花運', '不要留錢在手籽孙,近期將走財運', '留意新認識的人烈评,將遇改變?nèi)松馁F人', '走路留意,可能會走狗屎運', '放開吃喝犯建,三個月內(nèi)你不會發(fā)胖', '身邊有人正在準備一個驚喜給你');
var c = Math.floor(Math.random() * 6);
var renwu = new Array('富察容音', '弘歷', '魏瓔珞', '嫻妃', '高貴妃', '葉太醫(yī)', '富察·傅恒', '海蘭察', '陸晚晚', '明玉');
var a = Math.floor(Math.random() * 6);
var fan = new Array('因皇子去世一直耿耿于懷讲冠,內(nèi)心苦悶。富察容音常有胸悶适瓦、乳房疼痛的癥狀竿开,是情志失意導(dǎo)致的乳腺問題谱仪。', '前朝政務(wù)繁多,后宮妃嬪爭寵否彩,后宮女人幾乎都有乳腺困擾疯攒,皇上命葉太醫(yī)制出乳丹,幫助解決嬪妃的乳腺問題列荔。', '長期想著復(fù)仇敬尺,情志不暢,所以月經(jīng)紊亂肌毅,乳房有腫塊都不知道筷转。幸得葉太醫(yī)乳丹相助,幫其解決乳腺問題悬而。', '不能保家人周全呜舒,無奈黑化,也一直深受乳腺問題的煩惱笨奠。', '唯恐失去皇上寵愛袭蝗,天天苦于宮斗,飽受乳腺問題煩惱般婆。', '苦于沒有疑難雜癥給他醫(yī)治到腥,后被皇上指派解決嬪妃的乳腺問題,研發(fā)出乳丹蔚袍。', '因為沒有和心愛的女人在一起乡范,從而抱恨終身。', '心愛的女人在成親當(dāng)天自殺啤咽,讓海蘭察心痛一生晋辆。', '自身實力與家庭背景都很薄弱,不求富貴宇整,只求安保瓶佳。', '因體內(nèi)被純貴妃扎的針重傷加之受順?gòu)逄羲簦越鸺舨逍牧矍啵员M而亡霸饲。');
var xg = new Array('內(nèi)心溫柔,心胸寬廣臂拓,最終別人厚脉,也能得到別人尊重。', '愛憎分明埃儿、內(nèi)心驕傲器仗,做人做事不會選擇將就。', '客觀理智、內(nèi)心透徹精钮,內(nèi)心善良富有正義威鹿,重視承諾。', '追求單純但是內(nèi)心又自卑轨香,遇到失望的事情忽你,會變得偏執(zhí)。', '喜形于色臂容,為人處世情緒化科雳,從不壓抑內(nèi)心想法。', '本是江湖游醫(yī)卻救阿哥脓杉、激皇上(治苍忝亍)、懟太醫(yī)球散,萌萌的外表下藏著一顆濟世救人的醫(yī)者仁心尿赚。', '深得皇上的寵愛和重視,表面上看是一個冷清的人蕉堰,實際上是一個專情熱血的男子凌净。', '心性善良,智勇雙全屋讶,屢經(jīng)戰(zhàn)陣冰寻,注重研習(xí)兵法,受眾尊崇的將領(lǐng)皿渗。', '溫婉賢淑的大家閨秀斩芭,才貌出眾,天性善良乐疆,不爭名利秒旋,清新脫俗。', '性格直爽诀拭,忠肝義膽,說話毒舌但是心地善良煤蚌。');
var img = new Array('http://login.pink333.com/uploads/20180828/4c9b626b59d6a0b38a03089d1da4d906.jpg',
'http://login.pink333.com/uploads/20180828/d942b0f1bccc4e6c6081bd5f3398fd4e.jpg',
'http://login.pink333.com/uploads/20180828/29af4184e336f82a38ecd3de07a01569.jpg',
'http://login.pink333.com/uploads/20180828/eacea6d98f57fdcda835003fd8734c14.jpg',
'http://login.pink333.com/uploads/20180828/9416f7ac87e99efd8a179dedec15d0c0.jpg',
'http://login.pink333.com/uploads/20180828/1ee16bba3d950f8fce32d8e6d01025b3.jpg',
'http://login.pink333.com/uploads/20180828/2114ed95f319b23afa498b6064b90517.jpg',
'http://login.pink333.com/uploads/20180828/07682aa82440bd48bec9cfcdf8830fb0.jpg',
'http://login.pink333.com/uploads/20180828/2f71cd25f32922035c08071042cda134.jpg',
'http://login.pink333.com/uploads/20180828/ff6f46a6ad3c15200f1d380aa1ccde25.jpg');
if (a == 0) {
that.setData({
fan: fan[0],
xg: xg[0],
});
wx.getImageInfo({
src: '../../images/fcry.png',
success: function (res) {
console.log(res)
that.setData({
imgurl: '../../' + res.path
});
}
})
}
if (a == 1) {
that.setData({
fan: fan[1],
xg: xg[1]
});
wx.getImageInfo({
src: '../../images/hl.png',
success: function (res) {
console.log(res)
that.setData({
imgurl: '../../' + res.path
});
}
})
}
if (a == 2) {
that.setData({
fan: fan[2],
xg: xg[2]
});
wx.getImageInfo({
src: '../../images/wyl.png',
success: function (res) {
console.log(res)
that.setData({
imgurl: '../../' + res.path
});
}
})
}
if (a == 3) {
that.setData({
fan: fan[3],
xg: xg[3]
});
wx.getImageInfo({
src: '../../images/xf.jpg',
success: function (res) {
console.log(res)
that.setData({
imgurl: '../../' + res.path
});
}
})
}
if (a == 4) {
that.setData({
fan: fan[4],
xg: xg[4]
});
wx.getImageInfo({
src: '../../images/ggf.png',
success: function (res) {
console.log(res)
that.setData({
imgurl: '../../' + res.path
});
}
})
}
if (a == 5) {
that.setData({
fan: fan[5],
xg: xg[5]
});
wx.getImageInfo({
src: '../../images/yty.png',
success: function (res) {
console.log(res)
that.setData({
imgurl: '../../' + res.path
});
}
})
}
if (a == 6) {
that.setData({
fan: fan[6],
xg: xg[6]
});
wx.getImageInfo({
src: '../../images/fcfh.jpg',
success: function (res) {
console.log(res)
that.setData({
imgurl: '../../' + res.path
});
}
})
}
if (a == 7) {
that.setData({
fan: fan[7],
xg: xg[7]
});
wx.getImageInfo({
src: '../../images/hnc.png',
success: function (res) {
console.log(res)
that.setData({
imgurl: '../../' + res.path
});
}
})
}
if (a == 8) {
that.setData({
fan: fan[8],
xg: xg[8]
});
wx.getImageInfo({
src: '../../images/lww.png',
success: function (res) {
console.log(res)
that.setData({
imgurl: '../../' + res.path
});
}
})
}
if (a == 9) {
that.setData({
fan: fan[9],
xg: xg[9]
});
wx.getImageInfo({
src: '../../images/my.png',
success: function (res) {
console.log(res)
that.setData({
imgurl: '../../' + res.path
});
}
})
}
that.setData({
yuyan:yuyan[c],
renwu: renwu[a]
});
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面初次渲染完成
*/
onReady: function () {
var that = this;
var context = wx.createCanvasContext('share')
context.setStrokeStyle("#00ff00")
context.setLineWidth(1)
context.stroke()
context.draw(false, this.getTempFilePath)
},
//獲取臨時路徑
getTempFilePath: function () {
wx.canvasToTempFilePath({
canvasId: 'share',
success: (res) => {
this.setData({
shareTempFilePath: res.tempFilePath
})
}
})
},
/**
* 繪制多行文本耕挨,考慮到內(nèi)容過多可能會顯示不全,這里增加一個函數(shù)
*/
drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
var lineWidth = 0;
var lastSubStrIndex = 0; //每次開始截取的字符串的索引
for (let i = 0; i < str.length; i++) {
lineWidth += ctx.measureText(str[i]).width;
if (lineWidth > canvasWidth) {
ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //繪制截取部分
initHeight += 16; //16為字體的高度
lineWidth = 0;
lastSubStrIndex = i;
titleHeight += 30;
}
if (i == str.length - 1) { //繪制剩余部分
ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
}
}
// 標(biāo)題border-bottom 線距頂部距離
titleHeight = titleHeight + 10;
return titleHeight
},
//保存至相冊
saveImageToPhotosAlbum: function () {
var that = this;
var unit = that.data.screenWidth / 375
//2. canvas繪制文字和圖片
const ctx = wx.createCanvasContext('share');
var bgImgPath = that.data.shareImgSrc;
var fanstr = '前世煩惱:' + that.data.fan;
var rwxg = '人物性格:' + that.data.xg;
//這里是把頁面上的數(shù)據(jù)寫入到畫布里尉桩,具體的坐標(biāo)需要各位自行調(diào)整
ctx.drawImage(bgImgPath, 0, 0, 375, 580);
ctx.drawImage(that.data.shareImgPath, 50, 450, 284, 80);
ctx.drawImage(that.data.imgurl, 146, 100, 100, 100);
ctx.setFontSize(13)
ctx.setFillStyle('#5e7436')
ctx.fillText('姓名:' + that.data.cname, 50, 241)
ctx.fillText('人物匹配:' + that.data.renwu, 50, 271);
ctx.fillText('近期預(yù)言:' + that.data.yuyan, 50, 300);
this.drawText(ctx, fanstr, 50, 330, 145, 280);
this.drawText(ctx, rwxg, 50, 400, 145, 280);
//ctx.fillText('前世煩惱:' + that.data.fan, 50, 330);
//ctx.fillText('人物性格:' + that.data.xg, 50, 360);
ctx.stroke()
ctx.draw(false, function() {
// 3. canvas畫布轉(zhuǎn)成圖片
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 375,
height: 580,
destWidth: 375,
destHeight: 580,
canvasId: 'share',
success: function (res) {
console.log(res);
that.setData({
shareImgSrc: res.tempFilePath
})
if (!res.tempFilePath) {
wx.showModal({
title: '提示',
content: '圖片繪制中筒占,請稍后重試',
showCancel: false
})
}
//4. 當(dāng)用戶點擊分享到朋友圈時,將圖片保存到相冊
wx.saveImageToPhotosAlbum({
filePath: that.data.shareImgSrc,
success(res) {
console.log(res);
wx.showModal({
title: '圖片保存成功',
content: '圖片成功保存到相冊了蜘犁,去發(fā)圈噻~',
showCancel: false,
confirmText: '好噠',
confirmColor: '#72B9C3',
success: function (res) {
if (res.confirm) {
console.log('用戶點擊確定');
}
that.setData({
canvasHidden: true
})
}
})
}
})
},
fail: function (res) {
console.log(res)
}
})
});
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面顯示
*/
onShow: function () {
const that = this;
wx.downloadFile({
url: that.data.shareImgSrc,
success: function (res) {
that.data.shareImgSrc = res.tempFilePath
}, fail: function (res) {
}
})
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面隱藏
*/
onHide: function () {
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面卸載
*/
onUnload: function () {
},
/**
* 頁面相關(guān)事件處理函數(shù)--監(jiān)聽用戶下拉動作
*/
onPullDownRefresh: function () {
},
/**
* 頁面上拉觸底事件的處理函數(shù)
*/
onReachBottom: function () {
},
/**
* 用戶點擊右上角分享
*/
onShareAppMessage: function () {
}
})
通過以上方式我們就能輕松的把頁面轉(zhuǎn)換成圖片翰苫。希望本次教程對你有所幫助。