一、小程序保存海报,canvas绘制然后保存到相册
1.wxml
<view class="box-canvas">
<canvas canvas-id='myCanvas' class='myCanvas'></canvas>
</view>
<view class='myPage'>
<view class='myPage-title'>{
{myPageTitle}}</view>
<image class='myPage-img' src='{
{myPageImg}}'></image>
<view class='myPage-time'>{
{myPageTime}}</view>
<view class='myPage-msg'>
{
{myPageMsg}}
</view>
<view class='myPage-author'>{
{myPageAuthor}}</view>
</view>
<!-- 涉及授权,须用按钮 -->
<button bindtap='tosave' class='saveBtn'>保存</button>
2.wxss
/* 如果需要海报隐藏,可以给canvas套一个盒子,给这个盒子宽高置为零同时添加 overflow: hidden*/
/***
如果不添加,在编辑器中是好的,但在手机中,canvas的层级会盖住自己原来的页面
**/
.box-canvas {
width: 0;
height: 0;
overflow: hidden;
}
.myCanvas {
width: 375px;
height: 667px;
position:fixed;
left:9000px;
}
.myPage {
padding: 0 25rpx;
color: #ffe1c3;
}
.myPage-title{
width: 100%;
text-align: center;
font-size: 46rpx;
line-height: 80rpx;
margin: 10rpx 0;
}
.myPage-img{
width: 100%;
}
.myPage-time{
width: 100%;
font-size: 46rpx;
margin: 10rpx 0;
}
.myPage-msg{
width: 100%;
font-size: 36rpx;
line-height: 60rpx;
}
.myPage-author{
width: 100%;
font-size: 46rpx;
text-align: right;
margin: 10rpx 0;
}
.saveBtn{
width: 200rpx;
height: 50rpx;
line-height: 50rpx;
text-align: center;
font-size: 30rpx;
background-color: orange;
color: #fff;
border-radius: 50rpx;
margin: 50rpx auto 0;
}
3.js
var that;
var myPageTitle = "我是标题";
var myPageImg = "http://img-ads.youkuaiyun.com/2018/201812101159198567.png";
var myPageTime = "2018.12.24";
var myPageMsg = "这是段落这是段落这是段落这是段落这是段落这是段落这是段落 这是段落这是段落这是段落这是段落这是段落这是段落这是段落 这是段落这是段落这是段落这是段落这是段落这是段落这是段落";
var myPageAuthor = "出处";
Page({
/**
* 页面的初始数据
*/
data: {
//iscreating,是否正在画图
iscreating: false,
canvasPath: ''
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
that = this;
that.setData({
"myPageTitle": myPageTitle,
"myPageImg": myPageImg,
"myPageTime": myPageTime,
"myPageMsg": myPageMsg,
"myPageAuthor": myPageAuthor
});
},
/**
* 如果有过生成,那就保存
* 如果没生成过,那就先生成,再保存
* **/
tosave: function () {
if (that.data.canvasPath) {
that.redrawCanvasImage();
} else {
that.drawCanvasImage(myPageImg);
}
},
//重新保存图片
redrawCanvasImage: function () {
/**检测用户是否授权**/
wx.getSetting({
success: function (res) {
/**授权,则调用相册**/
if (res.authSetting["scope.writePhotosAlbum"] == true) {
that.saveimg();
} else if (res.authSetting["scope.writePhotosAlbum"] === false) {
/**未授权,则打开授权页面,让用户授权**/
wx.openSetting({
success: (res) => {
/**授权成功,则保存图片,失败则不保存**/
if (res.authSetting["scope.writePhotosAlbum"] == true) {
that.saveimg();
}
}
})
} else {
that.saveimg();
}
},
fail: function (res) {
console.log("打开设置失败", res)
}
})
},
// 画图