佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > 微信小程序之html5 canvas繪圖并保存到系統(tǒng)相冊

微信小程序之html5 canvas繪圖并保存到系統(tǒng)相冊

熱門標(biāo)簽:網(wǎng)站建設(shè) 硅谷的囚徒呼叫中心 檢查注冊表項 阿里云 使用U盤裝系統(tǒng) 智能手機(jī) 美圖手機(jī) 百度競價點(diǎn)擊價格的計算公式

開始實現(xiàn)之前先上個效果圖

 

tips

1.網(wǎng)絡(luò)圖片需先配置download域名,可通過wx.getImageInfo轉(zhuǎn)為臨時路徑;

2.個人習(xí)慣問題,我習(xí)慣使用async-await語法,所以需要引入regenerator這個庫,使用方式可網(wǎng)上查。

一、封裝通用微信api返回為Promise對象

/datas/common.js

// 封裝獲取微信圖片信息。
export const getWxImageInfo = (imgPath) => {
  return new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: imgPath,
      success: res => {
        resolve(res)
      },
      fail: res => {
        reject(res)
      }
    })
  })
}

// 封裝獲取節(jié)點(diǎn)選擇器信息
export const getSelectQurey = (queryStr) => {
  return new Promise(resolve => {
    var query = wx.createSelectorQuery();
    query.select(queryStr).boundingClientRect();
    query.exec(res => {
      resolve(res)
    })
  })
}

// 封裝把畫布導(dǎo)出生成指定大小的圖片
export const canvasToTempFilePath = (width, height, canvasId, fileType = 'jpg') => {
  return new Promise((resolve, reject) => {
    wx.canvasToTempFilePath({
      width,
      height,
      canvasId,
      fileType,
      success: res => {
        resolve(res)
      },
      fail: res => {
        reject(res)
      }
    })
  })
}

// 封裝保存圖片到系統(tǒng)相冊
export const saveImageToPhotosAlbum = (filePath) => {
  return new Promise((resolve, reject) => {
    wx.saveImageToPhotosAlbum({
      filePath,
      success: res => {
        resolve(res)
      },
      fail: res => {
        reject(res)
      }
    })
  })
}

二、視圖的實現(xiàn)

.wxml

<view class="icon-download" catchtap="getCanvas">點(diǎn)擊生成圖片</view>
<!-- 二維碼大圖 -->
<view class='shade' wx:if="{{isShowCanvas}}">
  <view class='qr-code'>
    <canvas class='qr-canvas' canvas-id="qrCanvas" id="qrCanvas"></canvas>
    <view class='qr-btn'>
      <view class='qr-btn-save' catchtap='saveImageToPhotosAlbumFunc'>保存圖片,分享到朋友圈</view>
      <view class='qr-btn-cancel' catchtap='hideCanvas'>取消</view>
    </view>
  </view>
</view>
<!-- 二維碼大圖.end -->

.wxss

/* 查看大圖 */
.shade {
  width: 100%;
  height: 100%;
  background-color: rgba(240, 235, 235, 0.5);
  position: fixed;
  z-index: 100;
  top: 0;
  left: 0;
}
.qr-code {
  width: 600rpx;
  height: 1000rpx;
  background-color: #fff;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* margin: 30rpx auto; */
}
.qr-canvas {
  display: block;
  background-color: #fff;
  margin: 0 auto;
  width: 600rpx;
  height: 900rpx;
}
.qr-btn {
  width: 600rpx;
  height: 100rpx;
  line-height: 100rpx;
  margin: 0 auto;
  font-size: 28rpx;
  color: #fff;
  display: flex;
  background-color: #658dc5;
}
.qr-btn-save {
  flex: 0 0 500rpx;
  text-align: center;
  border-right: 1rpx solid #fff;
}
.qr-btn-cancel {
  text-align: center;
  flex: 0 0 100rpx;
}

三、創(chuàng)建canvas并保存到系統(tǒng)相冊

tips

商品圖是正方形的,所以這里商品圖的寬高都用canvas的寬文字不能換行,這里只是簡單的處理了一下
 

注意: wx.canvasToTempFilePath(Object object, Object this) 這個的使用,文檔有一句話需要注意的:“把當(dāng)前畫布指定區(qū)域的內(nèi)容導(dǎo)出生成指定大小的圖片。在 draw() 回調(diào)里調(diào)用該方法才能保證圖片導(dǎo)出成功。”

const app = getApp()
const regeneratorRuntime = app.globalData.regeneratorRuntimeconst
const util = require('../../utils/util.js')
import {
  getSelectQurey,
  getWxImageInfo,
  canvasToTempFilePath,
  saveImageToPhotosAlbum
} from '../../datas/common.js'

Page({
  data: {
    isShowCanvas: false, // 是否顯示canvas    
    wxaCode: 'https://xxx..jpg', // 商品小程序碼
    goodsImageUrl: 'https://xxx..jpg', // 商品圖片    
    canvasTempFilePath: '', // canvas導(dǎo)出生成圖片的臨時路徑  
  },

  // 點(diǎn)擊顯示要生成的canvas  
  getCanvas(e) {
    if (!this.data.wxaCode) {
      util.showToast('二維碼生成失敗');
      return;
    }
    this.setData({
      isShowCanvas: true
    }, () => {
      this.createCanvas();
    })
  },

  // 隱藏canvas  
  hideCanvas() {
    this.setData({
      isShowCanvas: false
    })
  },

  // 創(chuàng)建canvas  
  async createCanvas() {
    wx.showLoading({
      title: '圖片生成中...'
    })
    const _this = this

    // 創(chuàng)建節(jié)點(diǎn)選擇器    
    const res = await getSelectQurey('#qrCanvas');

    // canvas的寬高    
    const cvWidth = res[0].width;
    const cvHeight = res[0].height;
    const cvSubValue = cvHeight - cvWidth
    const qrWidth = cvSubValue / 1.5
    const qrMargin = (cvSubValue - qrWidth) / 2
    const qrX = cvWidth - qrWidth - qrMargin / 2
    const qrY = cvWidth + qrMargin
    const shopNameY = cvWidth + cvSubValue - qrWidth

    // 二維碼網(wǎng)絡(luò)圖片轉(zhuǎn)臨時路徑    
    let qrImagePath = '';
    try {
      const wxaCode = _this.data.wxaCode;
      const qrImage = await getWxImageInfo(wxaCode);
      qrImagePath = qrImage.path
    } catch (e) {
      wx.hideLoading();
      this.hideCanvas();
      util.showToast('二維碼生成失敗');
      return;
    }

    // 商品網(wǎng)絡(luò)圖片轉(zhuǎn)臨時路徑    
    let goodsImagePath = '/images/default_goods.png';
    const goodsImage = _this.data.goodsImageUrl;
    if (goodsImage) {
      const goodsImageRes = await getWxImageInfo(goodsImage);
      goodsImagePath = goodsImageRes.path;
    }

    // 創(chuàng)建canvas    
    var ctx = wx.createCanvasContext('qrCanvas', _this);

    // 設(shè)置背景    
    ctx.setFillStyle('#fff');
    ctx.fillRect(0, 0, cvWidth, cvHeight);

    // 設(shè)置商品圖片 商品圖寬高是一樣的    
    ctx.drawImage(goodsImagePath, 0, 0, cvWidth, cvWidth);

    // 設(shè)置二維碼圖片    
    ctx.drawImage(qrImagePath, qrX, qrY, qrWidth, qrWidth);

    // 設(shè)置店鋪名稱    
    const shopName = '我是店鋪名稱';
    ctx.setFillStyle('black')
    ctx.setFontSize(16)
    ctx.setTextAlign('left')
    ctx.fillText(shopName, 10, shopNameY, cvWidth - qrWidth);

    // 設(shè)置商品名稱 文字不能換行,這里只是簡單的處理了一下    
    const goodsName = '一個名字很長很長的商品就問你怕不怕';
    let goodsName1 = '';
    let goodsName2 = '';
    ctx.setFillStyle('black')
    ctx.setFontSize(14)
    ctx.setTextAlign('left')
    if (goodsName.length <= 10) {
      ctx.fillText(goodsName, 10, shopNameY + 30, cvWidth - qrWidth);
    } else
    if (goodsName.length > 10 && goodsName.length <= 22) {
      goodsName1 = goodsName.substring(0, 10);
      goodsName2 = goodsName.substring(10);
      ctx.fillText(goodsName1, 10, shopNameY + 30, cvWidth - qrWidth);
      ctx.fillText(goodsName2, 10, shopNameY + 50, cvWidth - qrWidth);
    } else {
      goodsName1 = goodsName.substring(0, 10);
      goodsName2 = goodsName.substring(10, 22) + '...';
      ctx.fillText(goodsName1, 10, shopNameY + 30, cvWidth - qrWidth);
      ctx.fillText(goodsName2, 10, shopNameY + 50, cvWidth - qrWidth);
    }

    // 設(shè)置提示    
    const tipText = '長按識別小程序,馬上下單!';
    ctx.setFillStyle('gray')
    ctx.setFontSize(8)
    ctx.setTextAlign('center')
    ctx.fillText(tipText, cvWidth / 2, cvHeight - 10);

    // 完成    
    ctx.draw(false, () => {
      wx.hideLoading();
      _this.canvasToTempFilePathFunc(cvWidth, cvHeight, 'qrCanvas')
    });
  },

  // 把當(dāng)前畫布指定區(qū)域的內(nèi)容導(dǎo)出生成指定大小的圖片  
  async canvasToTempFilePathFunc(cvWidth, cvHeight, qrCanvas) {
    try {
      let res = await canvasToTempFilePath(cvWidth, cvHeight, qrCanvas);
      this.setData({
        canvasTempFilePath: res.tempFilePath
      });
    } catch (error) {
      console.log(error);
      util.showToast(error.errMsg);
    }
  },

  // 保存圖片到本地  
  async saveImageToPhotosAlbumFunc() {
    try {
      let res = await saveImageToPhotosAlbum(this.data.canvasTempFilePath);
      console.log(res);
      this.hideCanvas();
      util.showToast('圖片保存成功');
    } catch (err) {
      console.log(err);
    }
  }
})

寫得比較簡單,因為主要是方便自己做記錄的,所以也沒有考慮到過多的使用場景。

總結(jié)

以上所述是小編給大家介紹的微信小程序之html5 canvas繪圖并保存到系統(tǒng)相冊,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!

標(biāo)簽:湘潭 懷化 湖北 通遼 煙臺 黃山 山南 賀州

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《微信小程序之html5 canvas繪圖并保存到系統(tǒng)相冊》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    南木林县| 云南省| 宜宾县| 茂名市| 云安县| 自贡市| 太康县| 秦皇岛市| 历史| 武穴市| 涿鹿县| 泗水县| 图们市| 南投市| 噶尔县| 沭阳县| 金沙县| 榆中县| 左贡县| 明光市| 无锡市| 班戈县| 郓城县| 分宜县| 双流县| 普兰县| 攀枝花市| 平远县| 苍溪县| 石门县| 伊春市| 广西| 全州县| 巨野县| 泾川县| 雷州市| 忻州市| 安陆市| 昌平区| 五大连池市| 昭通市|