wxml:
<canvas
canvas-id="gameCanvas"
style="width:750rpx; height:350rpx"
hidden="{{!statusTag}}"
></canvas>
<button bindtap="createImage">生成圖片</button>
js
// pages/index/pic.js
Page({
/**
* 頁面的初始數據
*/
data: {
imagePath:'http://imgo2o.shikee.com/goods/2019/10/17/201910171144361688.jpg',
imageWidth:'',
imageHeight:'',
show:0,
statusTag:false
},
/**
* 生命周期函數--監聽頁面加載
*/
onLoad: function (options) {
},
/**
* 生命周期函數--監聽頁面初次渲染完成
*/
onReady: function () {
let _this = this,
deviceWidth = 0;
//獲取設備寬度,用於求所需畫在畫布上的圖片的高度
wx.getSystemInfo({
success:function(res){
deviceWidth = res.windowWidth; //獲取設備寬度
wx.getImageInfo({ //獲取圖片信息
src: _this.data.imagePath,
success: function(res){
let imageWidth = deviceWidth,
imageHeight = deviceWidth/res.width*res.height; //求所需畫在畫布上的圖片的高度
_this.setData({
'imageWidth': imageWidth,
'imageHeight':imageHeight
});
console.log(imageHeight);
const ctx = wx.createCanvasContext('gameCanvas'); //創建畫布對象
ctx.drawImage(_this.data.imagePath, 0, 0, imageWidth, imageHeight); //添加圖片
ctx.setFontSize(16); //設置字體大小
ctx.setFillStyle('blue'); //設置字體顏色
ctx.fillText('你的名字', imageWidth/2, imageHeight/2); //設置字體內容、坐標
ctx.draw(); //開始繪畫
}
})
}
});
},
createImage: function(){
this.setData({
statusTag:true
})
let imageWidth = this.data.imageWidth,
imageHeight = this.data.imageHeight;
wx.canvasToTempFilePath({ //將canvas生成圖片
canvasId: 'gameCanvas',
x: 0,
y: 0,
width: imageWidth,
height: imageHeight,
destWidth: imageWidth, //截取canvas的寬度
destHeight: imageHeight, //截取canvas的高度
success: function (res) {
wx.saveImageToPhotosAlbum({ //保存圖片到相冊
filePath: res.tempFilePath,
success: function () {
wx.showToast({
title: "生成圖片成功!",
duration: 2000
})
}
})
}
})
},
/**
* 生命周期函數--監聽頁面顯示
*/
onShow: function () {
},
/**
* 生命周期函數--監聽頁面隱藏
*/
onHide: function () {
},
/**
* 生命周期函數--監聽頁面卸載
*/
onUnload: function () {
},
/**
* 頁面相關事件處理函數--監聽用戶下拉動作
*/
onPullDownRefresh: function () {
},
/**
* 頁面上拉觸底事件的處理函數
*/
onReachBottom: function () {
},
/**
* 用戶點擊右上角分享
*/
onShareAppMessage: function () {
}
})
更多詳細的功能:https://www.cnblogs.com/gcjun/p/11724531.html
H5-canvas生成圖片案例:
鏈接:https://pan.baidu.com/s/1IRiHGeK-X4kC4or0Zj97Gw
提取碼:u15s
