微信小程序 —— canvas生成海报图与分享
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了微信小程序 —— canvas生成海报图与分享,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含9199字,纯文字阅读大概需要14分钟。
内容图文
整体思路
- 获取手机屏幕大小去依据设计尺寸比例调整
- 赋值图片路径
- canvas生产图片(要注意顺序)
- 获取用户相册权限
- 保存相册
效果图
代码示例
wxml
<view style="position: absolute;bottom: 0;left: 0;color:#000;z-index:99999">
坐标: ({{x*2}}, {{y*2}})
</view>
<block wx:if="{{canvasType}}">
<!-- style="background-image: url(/images/poster_Chinese.png); background-size: cover;" -->
<canvas class="canvas" canvas-id="shareCanvas" bindtouchstart="start" bindtouchmove="move" bindtouchend="end"></canvas>
</block>
<view class="transpond-box flexCenter" style='flex-direction:column' bindtap="shareBtn">
<image mode="widthFix" src="/images/icon_oyq.png" style="width:110rpx;height:110rpx;margin-bottom:16rpx;"></image>
<view>保存图片分享</view>
</view>
wxss
page {
background: #F0F5F8;
}
.canvas {
width: 100%;
height: 100%;
position: fixed;
z-index: 2;
/* top: 0; */
top: 999999rpx;
background-color: rgba(0, 0, 0, 0.3);
transform: scale(0.6);
}
.transpond-box {
position: absolute;
left: 0;
bottom: 0;
width: 100%;
height: 242rpx;
background: #FFFFFF;
padding: 14rpx;
}
js
// pages/test1/test1.js
Page({
/**
* 页面的初始数据
*/
data: {
canvasType: false, //canvas是否显示
name: '四字弟弟',
subject: 'xx',
bgImgUrl: 'http://xxx',
iconUrl: 'http://xxx',
qrcodeUrl: 'http://xxx',
x: 0,
y: 0,
hidden: true,
price: 100,
// canvas
canvasWidth: 0,
canvasHeight: 0,
loadType: false, //保存图片,分享好友 Btn
title: 'xxx'
},
start: function (e) {
this.setData({
hidden: false,
x: e.touches[0].x,
y: e.touches[0].y
})
},
move: function (e) {
this.setData({
x: e.touches[0].x,
y: e.touches[0].y
})
},
end: function (e) {
this.setData({
hidden: true
})
},
/**
* 生命周期函数--监听页面加载
*/
onl oad: function (options) {},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
wx.onUserCaptureScreen(function (res) {
console.log('用户截屏了')
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
if (res.from === 'button') {
// 来自页面内转发按钮
console.log(res.target)
}
return {
title: '',
path: '/page/user'
}
},
/**
* 开启转发朋友圈
*/
onShareTimeline(res) {
return {
title: '',
query: "",
bgImgUrl: ''
}
},
// 保存图片
shareBtn() {
this.getSysInfo()
setTimeout(() => {
this.btnTap()
}, 1000)
console.log("保存")
},
/*获取手机宽高*/
getSysInfo() {
let that = this
let bgImgUrl = this.data.bgImgUrl
let qrcodeUrl = this.data.qrcodeUrl
let iconUrl = this.data.iconUrl
wx.getSystemInfo({
success(res) {
that.setData({
canvasWidth: res.windowWidth,
canvasHeight: res.windowHeight
})
// 获取图片信息生成canvas
that.getImginfo([bgImgUrl, iconUrl, qrcodeUrl], 0);
}
})
},
// 获取图片信息
getImginfo: function (urlArr, _type) {
let that = this;
//console.log(urlArr, _type, "ssssssssssss")
wx.getImageInfo({
src: urlArr[_type], //服务器返回的带参数的小程序码地址
success: function (res) {
//res.path是网络图片的本地地址
if (_type === 0) { //背景图片
that.setData({
bgImgUrl: res.path,
})
that.getImginfo(urlArr, 1)
} else if (_type === 1) { //头像图片
that.setData({
iconUrl: res.path,
})
that.getImginfo(urlArr, 2)
} else {
that.setData({ //二维码
qrcodeUrl: res.path,
loadType: true,
})
// 创建canvas图片
that.canvasImg();
}
},
fail: function (res) {
//失败回调
console.log('错误-res', _type, res)
}
});
},
// (x,y):圆角矩形起始坐标; width: 矩形宽度; height: 矩形高度; r: 矩形圆角; bgcolor: 矩形填充颜色; lineColor: 矩形边框颜色;
draw(ctx, x, y, width, height, r, bgcolor, lineColor) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + width - r, y);
ctx.arc(x + width - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
ctx.lineTo(x + width, y + height - r);
ctx.arc(x + width - r, y + height - r, r, 0, Math.PI * 0.5);
ctx.lineTo(x + r, y + height);
ctx.arc(x + r, y + height - r, r, Math.PI * 0.5, Math.PI);
ctx.lineTo(x, y + r);
ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
ctx.fillStyle = bgcolor;
ctx.strokeStyle = lineColor;
ctx.fill();
ctx.stroke();
ctx.closePath();
},
// 生成图片 绘制canvas
canvasImg() {
let that = this;
wx.showLoading({
title: '图片正在生成'
});
that.setData({
canvasType: true
});
// 表头 40+88 =128
var header = 128;
var x = this.data.canvasWidth / 750; //设置相对canvas自适应根元素大小
console.log(x, "000000000000000")
const ctx = wx.createCanvasContext('shareCanvas');
ctx.drawImage(this.data.bgImgUrl, 0, 0, 750 * x, (1334 - header) * x);
// ctx.setTextAlign('center'); // 文字居中
ctx.beginPath() //注意此处
//名字
ctx.setFillStyle('#3C3C3C'); // 文字颜色 // ctx.setFontSize(17); // 文字字号
ctx.font = 'normal bold 17px sans-serif';
ctx.fillText(`${this.data.name}`, 272 * x, (790 - header) * x);
ctx.setFillStyle('#9D9D9D'); // 文字颜色
ctx.font = 'normal 400 13px sans-serif';
ctx.fillText(`${this.data.subject}当前级别 ${this.data.price}`, 272 * x, (842 - header) * x);
ctx.beginPath() //注意此处
ctx.moveTo(0, 1010 * x);
ctx.lineTo(750 * x, 1010 * x);
ctx.strokeStyle = "#F0F5F8";
ctx.stroke();
ctx.beginPath() //注意此处
ctx.setFillStyle('#9D9D9D'); // 文字颜色
ctx.font = 'normal 400 14px sans-serif';
ctx.fillText('xx', 87 * x, (1070 - header) * x);
ctx.setFillStyle('#9D9D9D'); // 文字颜色
ctx.font = 'normal 400 14px sans-serif';
ctx.fillText('xx', 335 * x, (1070 - header) * x);
ctx.setFillStyle('#9D9D9D'); // 文字颜色
ctx.font = 'normal 400 14px sans-serif';
ctx.fillText('xx', 609 * x, (1070 - header) * x);
ctx.setFillStyle('#008CD6'); // 文字颜色
ctx.font = 'normal 400 14px sans-serif';
ctx.fillText('xx', 35 * x, (1120 - header) * x);
ctx.setFillStyle('#9D9D9D'); // 文字颜色
ctx.font = 'normal 400 17px sans-serif';
ctx.fillText('/', 230 * x, (1120 - header) * x);
ctx.setFillStyle('#008CD6'); // 文字颜色
ctx.font = 'normal 400 14px sans-serif';
ctx.fillText('xx', 292 * x, (1120 - header) * x);
ctx.setFillStyle('#9D9D9D'); // 文字颜色
ctx.font = 'normal 400 17px sans-serif';
ctx.fillText('/', 495 * x, (1120 - header) * x);
ctx.beginPath() //注意此处
ctx.setFillStyle('#008CD6'); // 文字颜色
ctx.font = 'normal 400 14px sans-serif';
ctx.fillText('xx', 548 * x, (1120 - header) * x);
ctx.beginPath() //注意此处
let textLength = ctx.measureText(this.data.title).width
// 长度按照文字长度计算 218 * x
// that.draw(ctx, 498 * x, (848 - header) * x, 218 * x, 43 * x, 5, '#fff', '#008CD6')
let rectX = (708 * x) - textLength - 5 //476 * x
that.draw(ctx, rectX, (848 - header) * x, textLength + 10, 43 * x, 5, '#fff', '#008CD6')
ctx.beginPath() //注意此处
ctx.setFillStyle('#008CD6'); // 文字颜色
ctx.font = 'normal 400 14px sans-serif';
ctx.textAlign = "right";
ctx.fillText(`${this.data.title}`, 708 * x, (878 - header) * x);
console.log(ctx.measureText(this.data.title).width, "文字长度!!!")
ctx.setFillStyle('#3C3C3C'); // 文字颜色
ctx.font = 'normal bold 35px sans-serif';
ctx.fillText('xx', 710 * x, (980 - header) * x);
ctx.beginPath() //注意此处
//方形二维码框
ctx.fillStyle = "#fff";
ctx.fillRect(560 * x, (1144 - header) * x, 160 * x, 160 * x);
ctx.drawImage(this.data.qrcodeUrl, 570 * x, (1154 - header) * x, 140 * x, 140 * x);
ctx.closePath() //注意此处
ctx.beginPath() //注意此处
//圆形头像框
ctx.setStrokeStyle('rgba(0,0,0,.1)');
ctx.arc(150 * x, (778 - header) * x, 90 * x, 0, 2 * Math.PI);
ctx.fill('#fff');
//头像
ctx.clip();
ctx.drawImage(this.data.iconUrl, 60 * x, (688 - header) * x, 180 * x, 180 * x);
ctx.closePath() //注意此处
ctx.save() //状态的保存,-----改变了保存的位置 ctx.restore(); //状态的恢复
ctx.stroke();
ctx.draw();
wx.hideLoading();
},
// 授权 getSetting检测用户有没有开启相册权限 有的话直接保存 没有的话弹到权限页面让用户授权
btnTap: function () {
let that = this;
wx.showLoading({
title: '正在保存',
mask: true,
});
wx.getSetting({
success(res) {
if (res.authSetting['scope.writePhotosAlbum']) {
that.saveImg();
} else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
wx.authorize({
scope: 'scope.writePhotosAlbum',
success() {
that.saveImg();
},
fail() {
wx.showToast({
title: '您没有授权,无法保存到相册',
icon: 'none'
})
}
})
} else {
wx.openSetting({
success(res) {
if (res.authSetting['scope.writePhotosAlbum']) {
that.saveImg();
} else {
wx.showToast({
title: '您没有授权,无法保存到相册',
icon: 'none'
})
}
}
})
}
}
})
},
// 保存图片
saveImg: function () {
wx.canvasToTempFilePath({
canvasId: 'shareCanvas',
success: function (res) {
console.log(res)
wx.hideLoading();
var tempFilePath = res.tempFilePath;
wx.saveImageToPhotosAlbum({
filePath: tempFilePath,
success(res) {
wx.showModal({
content: '海报保存成功,你可以从手机相册中把海报分享到朋友圈',
showCancel: false,
confirmText: '好的',
confirmColor: '#333',
success: function (res) {
// wx.showToast({
// title: '保存成功',
// icon: 'none'
// });
if (res.confirm) {
var arr = [];
arr.push(tempFilePath);
//保存后全屏显示
wx.previewImage({
urls: arr,
current: arr
});
}
},
fail: function (err) {
console.log(err);
if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
console.log("用户一开始拒绝了,我们想再次发起授权")
alert('打开设置窗口')
wx.openSetting({
success(settingdata) {
console.log(settingdata)
if (settingdata.authSetting['scope.writePhotosAlbum']) {
console.log('获取权限成功,给出再次点击图片保存到相册的提示。')
} else {
console.log('获取权限失败,给出不给权限就无法正常使用的提示')
}
}
})
}
wx.showToast({
title: '弹窗失败',
icon: 'none'
});
}
})
},
fail: function (res) {
wx.showToast({
title: '没有相册权限',
icon: 'none',
duration: 2000
});
}
})
}
});
}
})
内容总结
以上是互联网集市为您收集整理的微信小程序 —— canvas生成海报图与分享全部内容,希望文章能够帮你解决微信小程序 —— canvas生成海报图与分享所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。