微信小程序canvas分享海報功能
更新時間:2019年10月31日 11:29:54 作者:IT光頭
這篇文章主要為大家詳細介紹了微信小程序canvas分享海報功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
微信小程序canvas分享海報,包含拒絕授權(quán)后重新打開授權(quán)設(shè)置。
這篇文章完善了第一次拒絕授權(quán)后再次點擊可以打開授權(quán)設(shè)置,希望可以幫助到愛學(xué)習(xí)的道友
這里是效果圖,圖片可以百度上找。

話不多說,直接上代碼
最重要的一點,千萬不要忘記在json文件里面注冊組件和wxml里面引用組件
wxml
<button class='btn' catchtap='createPoster' >生成海報</button>
<my-poster id="getPoster" types="{{type}}" isflag="{{isflag}}" title="{{goods_title}}" bigImg="{{share.img}}" qrcode="{{share.rcode}}" >
</my-poster>
js
data:{ isflag: false // 海報模態(tài)框 }
// 生成海報
createPoster:function(){
this.setData({
isflag: true
})
this.selectComponent('#getPoster').getAvaterInfo();
},
組件wxml
<view hidden="{{!isflag}}" catchtouchmove="return" class="con-poster" bindtap='closePoster'>
<!-- 模態(tài)框 -->
<view class='modialog'>
<view class='canvas-box' id='canvas-container'>
<canvas canvas-id="myCanvas" style="width:100%;height:100%;"/>
</view>
</view>
<!-- 保存圖片按鈕 -->
<view class='save-img' catchtap='saveBtn'>保存圖片</view>
</view>
組件wxss
.con-poster{
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
position: fixed;
top: 0;
left: 0;
z-index: 999;
}
.modialog{
width: 660rpx;
height: 750rpx;
margin: 100rpx auto 0;
}
.canvas-box{
width: 660rpx;
height: 750rpx;
background: #fff;
}
.save-img{
width: 660rpx;
height: 100rpx;
margin: 30rpx auto 0;
font-size: 32rpx;
display: flex;
justify-content: center;
align-items: center;
color: #fff;
background:linear-gradient(90deg,rgba(56,219,248,1),rgba(81,171,255,1));
}
組件js
properties: {
isflag:{ // 控制組件開關(guān)
type: Boolean,
value: true
}
bigImg:{ // 大圖
type: String,
value: ''
},
qrcode:{ // 二維碼
type: String,
value: ''
},
title:{ // 標題
type: String,
value: '大幅度開發(fā)'
}
}
data: {
imgHeight: 0
},
methods: {
//關(guān)閉海報
closePoster: function () {
this.setData({
isflag: false
})
},
// 提示框
toast: function(msg,callback){
wx.showToast({
title: msg,
icon: 'none',
success(){
callback && (setTimeout(function(){
callback()
},1500))
}
})
},
//下載產(chǎn)品大圖
getAvaterInfo: function () {
wx.showLoading({
title: '生成中...',
mask: true
});
var that = this;
that.setData({
isflag: true
})
var productImage = that.data.bigImg;
if (productImage) {
wx.downloadFile({
url: productImage,
success: function (res) {
wx.hideLoading();
if (res.statusCode === 200) {
var productSrc = res.tempFilePath;
that.calculateImg(productSrc, function (data) {
that.getQrCode(productSrc, data);
})
} else {
that.toast('產(chǎn)品圖片下載失敗!', () =>{
var productSrc = "";
that.getQrCode(productSrc);
})
}
},
fail: function (err) {
wx.hideLoading();
that.toast('請求失敗,網(wǎng)絡(luò)錯誤', () => {
that.closePoster()
})
}
})
} else {
wx.hideLoading();
var productSrc = "";
that.getQrCode(productSrc);
}
},
//下載二維碼
getQrCode: function (productSrc, imgInfo = "") {
wx.showLoading({
title: '生成中...',
mask: true,
});
var that = this;
var productCode = that.data.qrcode;
if (productCode) {
wx.downloadFile({
url: productCode,
success: function (res) {
wx.hideLoading();
if (res.statusCode === 200) {
var codeSrc = res.tempFilePath;
that.sharePosteCanvas(productSrc, codeSrc, imgInfo);
} else {
that.toast('二維碼下載失??!', () => {
var codeSrc = "";
that.sharePosteCanvas(productSrc, codeSrc, imgInfo);
})
}
},
fail: function () {
wx.hideLoading();
that.toast('請求失敗,網(wǎng)絡(luò)錯誤', () => {
that.closePoster()
})
}
})
} else {
wx.hideLoading();
var codeSrc = "";
that.sharePosteCanvas(productSrc, codeSrc);
}
},
//canvas繪制分享海報
sharePosteCanvas: function (avaterSrc, codeSrc, imgInfo){
wx.showLoading({
title: '生成中...',
mask: true,
})
var that = this;
const ctx = wx.createCanvasContext('myCanvas', that);
var width = "";
const query = wx.createSelectorQuery().in(this);
query.select('#canvas-container').boundingClientRect(function (rect) {
var width = rect.width;
var height = rect.height;
var left = rect.left;
ctx.setFillStyle('#fff');
ctx.fillRect(0, 0, width, height);
//海報大圖
if (avaterSrc) {
if (imgInfo) {
var imgheght = parseFloat(imgInfo);
}
ctx.drawImage(avaterSrc, 0, 0, width, imgheght ? imgheght : width);
ctx.setFontSize(14);
ctx.setFillStyle('#fff');
ctx.setTextAlign('left');
}
//海報標題
if (that.data.title) {
const CONTENT_ROW_LENGTH = 22; // 正文 單行顯示字符長度
let [contentLeng, contentArray, contentRows] = that.textByteLength((that.data.title).substr(0, 40), CONTENT_ROW_LENGTH);
ctx.setTextAlign('left');
ctx.setFillStyle('#000');
ctx.setFontSize(15);
let contentHh = 22 * 1;
for (let m = 0; m < contentArray.length; m++) {
ctx.fillText(contentArray[m], 15, imgheght + 35 + contentHh * m);
}
}
// 繪制二維碼
if (codeSrc) {
ctx.drawImage(codeSrc, left + 215, imgheght + 20, width / 4, width / 4)
ctx.setFontSize(10);
ctx.setFillStyle('#000');
}
}).exec()
setTimeout(function () {
ctx.draw();
wx.hideLoading();
}, 1000)
},
// 封裝每行顯示的文本字數(shù)
textByteLength(text, num) { // text為傳入的文本 num為單行顯示的字節(jié)長度
let strLength = 0;
let rows = 1;
let str = 0;
let arr = [];
for (let j = 0; j < text.length; j++) {
if (text.charCodeAt(j) > 255) {
strLength += 2;
if (strLength > rows * num) {
strLength++;
arr.push(text.slice(str, j));
str = j;
rows++;
}
} else {
strLength++;
if (strLength > rows * num) {
arr.push(text.slice(str, j));
str = j;
rows++;
}
}
}
arr.push(text.slice(str, text.length));
return [strLength, arr, rows] // [處理文字的總字節(jié)長度,每行顯示內(nèi)容的數(shù)組,行數(shù)]
},
//計算圖片尺寸
calculateImg: function (src, cb) {
var that = this;
wx.getSystemInfo({
success(res2) {
var imgHeight = (res2.windowWidth * 0.65) + 130;
that.setData({
imgHeight: imgHeight
})
cb(imgHeight - 130);
}
})
},
// 點擊保存按鈕
saveBtn(){
var _this = this
wx.getSetting({
success(res) {
if (res.authSetting['scope.writePhotosAlbum']) { // 第一次授權(quán),并且成功
_this.saveShareImg();
} else if (res.authSetting['scope.writePhotosAlbum'] === undefined) { // 未授權(quán)
wx.authorize({
scope: 'scope.writePhotosAlbum',
success() {
_this.saveShareImg();
},
fail() {
_this.toast('您沒有授權(quán),無法保存到相冊')
}
})
} else { // 第一次授權(quán)失敗,現(xiàn)在打開設(shè)置
wx.showModal({
title: '警告',
content: '請打開授權(quán),否則無法將圖片保存在相冊中!',
success(result) {
if (result.confirm) {
wx.openSetting({
success(settingResult) {
if (settingResult.authSetting['scope.writePhotosAlbum']) {
_this.saveShareImg();
} else {
_this.toast('您沒有授權(quán),無法保存到相冊')
}
}
})
}
}
})
}
}
})
},
// 保存到相冊
saveShareImg: function () {
var that = this;
wx.showLoading({
title: '正在保存',
mask: true,
})
setTimeout(function () {
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
success: function (res) {
var tempFilePath = res.tempFilePath;
wx.saveImageToPhotosAlbum({
filePath: tempFilePath,
success() { // 保存
wx.hideLoading()
that.toast('圖片保存成功', () =>{
that.closePoster();
})
},
fail: function (err) { // 取消保存
wx.hideLoading()
that.toast('保存失敗')
}
})
}
}, that);
}, 1000);
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于Bootstrap彈出框無法調(diào)用問題的解決辦法
這篇文章主要介紹了關(guān)于Bootstrap彈出框無法調(diào)用問題的解決辦法的相關(guān)資料,需要的朋友可以參考下2016-03-03

