本文實(shí)例講述了微信小程序?qū)崿F(xiàn)的canvas合成圖片功能。分享給大家供大家參考,具體如下:
創(chuàng)新互聯(lián)自2013年起,先為竹溪等服務(wù)建站,竹溪等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為竹溪企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
先要獲取圖片的信息 然后將需要合成的內(nèi)容用canvas繪制出來,得到一個(gè)合成好的畫布,接下來用 wx.canvasToTempFilePath 把當(dāng)前畫布指定區(qū)域的內(nèi)容導(dǎo)出生成指定大小的圖片,并返回文件路徑。這個(gè)時(shí)候的路徑 是微信的臨時(shí)路徑,瀏覽器是訪問不了的,因此需要請求服務(wù)器 用 wx.uploadFile 將本地資源上傳到開發(fā)者服務(wù)器。
在頁面的wxml中加入canvas組件如下:
<view class="canvasBox"> <canvas canvas-id="shareCanvas" ></canvas> </view>
在js中
picture: function () { //生成圖片
let that = this;
let p1 = new Promise(function (resolve, reject) {
wx.getImageInfo({
src: 圖片路徑,
success(res) {
resolve(res);
}
})
}).then(res => {
const ctx = wx.createCanvasContext('shareCanvas');
ctx.drawImage(res.path, 0, 0, 375, 300); //繪制背景圖
//ctx.setTextAlign('center') // 文字居中
ctx.setFillStyle('#000000') // 文字顏色:黑色
ctx.setFontSize(20) // 文字字號(hào):22px
ctx.fillText("文本內(nèi)容", 20, 70) //開始繪制文本的 x/y 坐標(biāo)位置(相對(duì)于畫布)
ctx.stroke();//stroke() 方法會(huì)實(shí)際地繪制出通過 moveTo() 和 lineTo() 方法定義的路徑。默認(rèn)顏色是黑色
ctx.draw(false, that.drawPicture());//draw()的回調(diào)函數(shù)
console.log(res.path);
})
},
drawPicture: function () { //生成圖片
var that = this;
setTimeout(function(){
wx.canvasToTempFilePath({ //把當(dāng)前畫布指定區(qū)域的內(nèi)容導(dǎo)出生成指定大小的圖片,并返回文件路徑
x: 0,
y: 0,
width: 375,
height: 300,
destWidth: 750, //輸出的圖片的寬度(寫成width的兩倍,生成的圖片則更清晰)
destHeight: 600,
canvasId: 'shareCanvas',
success: function (res) {
console.log(res);
that.draw_uploadFile(res);
},
})
},300)
},
draw_uploadFile: function (r) { //wx.uploadFile 將本地資源上傳到開發(fā)者服務(wù)器
let that = this;
wx.uploadFile({
url: 圖片上傳接口, //線上接口
filePath: r.tempFilePath,
name: 'imgFile',
success: function (res) {
console.log(res);
if(res.statusCode==200){
res.data = JSON.parse(res.data);
let imgsrc = res.data.data.src;
that.setData({
imgPath: imgsrc
});
}else{
console.log('失敗')
}
},
})
},
注意:若是將此方法寫成自定義組件,則 wx.createCanvasContext 和 wx.canvasToTempFilePath 都需要多傳一個(gè)this,

因在自定義組件下,當(dāng)前組件實(shí)例的this,用以操作組件內(nèi) <canvas/> 組件。
至于分享的話 ,拿到服務(wù)器返回的圖片路徑之后 就可以用來寫分享的圖片路徑了
希望本文所述對(duì)大家微信小程序開發(fā)有所幫助。
本文標(biāo)題:微信小程序?qū)崿F(xiàn)的canvas合成圖片功能示例
網(wǎng)站路徑:http://chinadenli.net/article38/gdpcsp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供移動(dòng)網(wǎng)站建設(shè)、網(wǎng)站導(dǎo)航、手機(jī)網(wǎng)站建設(shè)、品牌網(wǎng)站制作、企業(yè)網(wǎng)站制作、云服務(wù)器
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)