wxml:
<view class='kuai'>
<button bindtap='sharecard'>点击生成分享的canvas</button>
</view>
<view class='cancaslist' style='height:0;width:0;overflow:hidden'>
<canvas style='height:{{height}}px;width:{{width}}px' canvas-id='fristCanvas'></canvas>
</view>
js:
sharecard:function(){
var that = this;
wx.showLoading({
title: '图片生成中...',
})
var width="";
wx.getSystemInfo({
success: function (res) {
width = res.windowWidth
},
})
that.setData({
width:width
})
console.log(that.data.height, that.data.width)
const ctx = wx.createCanvasContext('fristCanvas')
ctx.setFillStyle('#fff')
ctx.fillRect(0, 0, that.data.width, that.data.height)
// 画图片
var topImg = that.data.canvastopimg;
ctx.drawImage(topImg, width * 0.05, 0, width * 0.9, width * 0.9)
// 画圆
ctx.arc(width - 50, width - 10, 50, 0, 2 * Math.PI)
ctx.setFillStyle('#666')
ctx.fill()
// 写字
ctx.setFontSize(16)
ctx.setFillStyle("#009ef9")
var cardwrite = "长按识别小程序码";
ctx.fillText(cardwrite, width - 130, width +50);
ctx.fillText('Hello', 30, width)
// 控制字数
ctx.setFillStyle("red")
var str="我是中国人,我爱我的祖国,老规矩地方官简单覅科技有限公司来电恢复蝴蝶谷东风路口和广泛地的复合弓"
console.log(str.length)
if (str.length > 16) {
var str1 = str.slice(0, 16);
var str2 = str.slice(16, 26) + "...";
ctx.fillText(str1, 30, width + 20);
ctx.fillText(str2, 30, width + 40);
} else {
ctx.fillText(str, 30, width + 20);
}
ctx.draw()
// 先出现loding图,1s后展示画布
setTimeout(function () {
that.drawAfter('fristCanvas');
}, 1000);
},
// 这个函数是条状到画布并且能够展示出来
drawAfter: function (fristCanvas) {
var that = this;
console.log('aaa');
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: that.data.width,
height: that.data.height,
canvasId: fristCanvas,
fileType: 'jpg',
success: function (res) {
wx.hideLoading();
console.log(res.tempFilePath)
wx.previewImage({
current: '', // 当前显示图片的http链接
urls: [res.tempFilePath] // 需要预览的图片http链接列表
})
},
complete: function (res) {
console.log(res);
}
})
}