微信小程序分享之生成海報--canvas


首先看文檔 了解知識點~~(https://developers.weixin.qq.com/miniprogram/dev/component/

githup:https://github.com/ad-skylar/wxProjece_canvas

一.畫布

1.wxml 創建canvas 

canvas-id canvas 組件的唯一標識符,若指定了 type 則無需再指定該屬性

 <canvas  style="width: 375px;height: 667px;position:fixed;" canvas-id="mycanvas"/>

 

2.js 調用wx.createCanvasContext

var context = wx.createCanvasContext('mycanvas');

3.繪制一個矩形作為背景,填充白色

CanvasContext.fillRect(x, y, width,height);

參數依次是 矩形x坐標、y坐標、圖片寬、高

填充一個矩形。用 setFillStyle 設置矩形的填充色,如果沒設置默認是黑色。

4.繪制圖像到畫布

CanvasContext.drawImage(src, x, y,width,height)

參數依次是圖片地址、x坐標、y坐標、圖片寬、高

5.繪制文字到畫布

CanvasContext.fillText(text, x, y, maxWidth)

參數依次是文本內容、x坐標、y坐標、需要繪制的最大寬度,可選

6.設置字體顏色,大小,位置等等看看文檔就ok了

 

二、保存圖片到系統相冊。調用前需要 用戶授權 scope.writePhotosAlbum。

wx.saveImageToPhotosAlbum({
  success(res) { }
})

 

 

 

代碼:share.wxml
<!--pages/share/share.wxml-->
<view>
  <image src="{{img}}" mode="widthFix" class='bgImg'></image>
  <view class="shareText">
    <text class='text'>從前從前有個人愛你很久,但偏偏風漸漸把距離吹的好遠。</text>
    <text class='text text2'> ———— 周傑倫《晴天》</text>
  </view>
  
  <view class='imgBox'>
    <button open-type="share" class='zfbtn'>
      <image src="{{wechat}}" class='img'></image>
       <text class='btntxt'>分享給朋友</text>
    </button>
    <button class='zfbtn m_l' bindtap='formSubmit'>
      <image src="{{xiazai}}" class='img'></image>
      <text class='btntxt'>生成海報</text>
    </button>
  </view>

  <!--生成海報  -->
    <view class='imagePathBox' hidden="{{maskHidden == false}}">
      <image src="{{imagePath}}" class='shengcheng'></image>
      <button class='baocun' bindtap='baocun'>保存相冊,分享到朋友圈</button>
    </view>
   <view hidden="{{maskHidden == false}}" class="mask"></view> 
  <view class="canvas-box">
      <canvas  style="width: 375px;height: 667px;position:fixed;" canvas-id="mycanvas"/>
  </view>  
</view>

share.js

const app = getApp()
Page({
  /**
   * 頁面的初始數據
   */
  data: {
    img: "../../images/me.jpg",
    wechat: "../../images/wechat.png",
    xiazai: "../../images/xiazai.png",
    share:"../../images/share.png",
    maskHidden: false,
    name: "",
  },
  /**
   * 生命周期函數--監聽頁面加載
   */
  onLoad: function (options) {
  },
  //將canvas轉換為圖片保存到本地,然后將圖片路徑傳給image圖片的src
  createNewImg: function () {
    var that = this;
    var context = wx.createCanvasContext('mycanvas');
    context.setFillStyle("#fff")
    context.fillRect(0, 0, 375, 667)
    var path = "/images/me.jpg";
    context.drawImage(path, 56, 56, 262, 349);
    var path5 = "/images/code.jpg";
    var path2 = "/images/text.png";
    var name = that.data.name;
    context.drawImage(path2, 56, 400, 263, 121);
  
    //繪制左下角文字
    context.setFontSize(14);
    context.setFillStyle('#333');
    context.setTextAlign('left');
    context.fillText("長按識別小程序", 70, 560);
    context.stroke();
    context.setFontSize(14);
    context.setFillStyle('#333');
    context.setTextAlign('left');
    context.fillText("跟我一起來學習吧~~", 70, 580);
    context.stroke();
   
    //繪制右下角小程序二維碼
    context.drawImage(path5, 230, 530,80,80);

    context.draw();
    //將生成好的圖片保存到本地
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          that.setData({
            imagePath: tempFilePath,
            canvasHidden: true
          });
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 200);
  },
  //點擊保存到相冊
  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '海報已保存到相冊',
          showCancel: false,
          confirmText: '確定',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              console.log('用戶點擊確定');
              /* 該隱藏的隱藏 */
              that.setData({
                maskHidden: false
              })
            }
          }, fail: function (res) {
            console.log(11111)
          }
        })
      }
    })
  },
  //點擊生成
  formSubmit: function (e) {
    var that = this;
    this.setData({
      maskHidden: false
    });
    wx.showToast({
      title: '海報生成中...',
      icon: 'loading',
      duration: 1000
    });
    setTimeout(function () {
      wx.hideToast()
      that.createNewImg();
      that.setData({
        maskHidden: true
      });
    }, 1000)
  },

  /**
   * 生命周期函數--監聽頁面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函數--監聽頁面顯示
   */
  onShow: function () {
    var that = this;
    wx.getUserInfo({
      success: res => {
        console.log(res.userInfo, "huoqudao le ")
        this.setData({
          name: res.userInfo.nickName,
        })
      }
    })
  },

  /**
   * 生命周期函數--監聽頁面隱藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函數--監聽頁面卸載
   */
  onUnload: function () {

  },

  /**
   * 頁面相關事件處理函數--監聽用戶下拉動作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 頁面上拉觸底事件的處理函數
   */
  onReachBottom: function () {

  },

  /**
   * 用戶點擊右上角分享
   */
  onShareAppMessage: function (res) {
    return {
      title: "一起來學習小程序吧~",
      success: function (res) {
        console.log(res, "轉發成功")
      },
      fail: function (res) {
        console.log(res, "轉發失敗")
      }
    }
  }
})
share.wxss
/* pages/share/share.wxss */
.bgImg{
  display: block;
  width: 70%;
  height: 366rpx;
  margin: 5% 15%;
}
.shareText{
  color: #333;
  font-size: 28rpx;
  margin-top: 50rpx;
  display: flex;
  flex-direction: column;
  align-content: center;
  justify-content: center;
}
.shareText .text{
  line-height: 60rpx;
  width: 100%;
  padding: 0 15%;
  box-sizing: border-box;
  display: block;
  color: #333;
}
.shareText .text2{
  text-align: right;
}
.btntxt{
   color: #333;
     font-size: 26rpx;
}
.imgBox{
  text-align: center;
  width: 100%;
  margin-top:60rpx;
  padding-bottom: 120rpx;
  display: flex;
}
.img{
  display: inline-block;
  width: 100%;
  height: 100%;
}
.m_l{
  margin-left: 180rpx;
}
.zfbtn{
  display:flex;
  flex-direction: column;
  font-size: 28rpx;
  align-items: center;
  justify-content: center;
  background: #fff;
}
.zfbtn image{
  width: 70rpx;
  height: 70rpx;
}
button[class="zfbtn"]::after {
  border: 0;
} 
button[class="zfbtn m_l"]::after {
  border: 0;
} 
.imagePathBox{
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.7);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10;
}
.shengcheng{
  width: 80%;
  height: 80%;
  position: fixed;
  top: 50rpx;
  left: 50%;
  margin-left: -40%;
  z-index: 10;
}
.baocun{
  display: block;
  width: 80%;
  height: 70rpx;
  padding: 0;
  line-height: 70rpx;
  text-align: center;
  position: fixed;
  bottom: 50rpx;
  left: 10%;
  color: #fff;
  font-size: 32rpx;
  border-radius: 24rpx;
  background: #fdd668;

}
button[class="baocun"]::after{
  border: 0;
}

iconfont下載的

 

 

 

 歌詞是我自己分享頁寫好的直接截圖了。canvas我排版有點難看哦,直接把圖片畫上去了。大家自己寫哦,不要學我懶省事。照片是我自己隨便找的,4:3的,一般手機拍的大多都是這個比例~~

總結下 自己留存 -.-


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM