js:
Ctx.arc(x,y,r,0,Math.PI,true);是画半圆
Ctx.arc(x,y,r,0,2Math.PI,true);画整个圆
uni-app官网介绍canvas绘图位置
小程序记得设置downloadFile添加图片域名
另外:
- html2canvas 将DOM转化为canvas,也就是把页面内容转化为图片
- 小程序生成海报 painter:https://github.com/Kujiale-Mobile/Painter uni-app painter插件
<canvas style="width: 622rpx; height: 1160rpx;" canvas-id="firstCanvas" id="firstCanvas" class="content"></canvas>
// 文字超过2行省略
textPrewrap(ctx, content, drawX, drawY, lineHeight, lineMaxWidth, lineNum) {
var drawTxt = ''; // 当前绘制的内容
var drawLine = 1; // 第几行开始绘制
var drawIndex = 0; // 当前绘制内容的索引
// 判断内容是否可以一行绘制完毕
if (ctx.measureText(content).width <= lineMaxWidth) {
ctx.fillText(content.substring(drawIndex, i), drawX, drawY);
} else {
for (var i = 0; i < content.length; i++) {
drawTxt += content[i];
if (ctx.measureText(drawTxt).width >= lineMaxWidth) {
if (drawLine >= lineNum) {
ctx.fillText(content.substring(drawIndex, i) + '..', drawX, drawY);
break;
} else {
ctx.fillText(content.substring(drawIndex, i + 1), drawX, drawY);
drawIndex = i + 1;
drawLine += 1;
drawY += lineHeight;
drawTxt = '';
}
} else {
// 内容绘制完毕,但是剩下的内容宽度不到lineMaxWidth
if (i === content.length - 1) {
ctx.fillText(content.substring(drawIndex), drawX, drawY);
}
}
}
}
},
// 绘海报
drawCanvas() {
var that = this;
var app = getApp();
var device = wx.getSystemInfoSync();
var width = device.windowWidth;//设备屏幕宽度
var xs = width / 375; // 自适应各种屏幕宽度
let ctx = uni.createCanvasContext('firstCanvas',that)
ctx.setFillStyle('#FFFFFF')
ctx.fillRect(0, 0, 311*xs, 580*xs)
uni.downloadFile({
url: that.currentImage, //不能直接获取网络图片,需要先把图片存到本地,然后在放入画板
success: function (res) {
ctx.drawImage(res.tempFilePath,0,0,311*xs,311*xs)
ctx.save()
ctx.setFontSize(30*xs) // 设置字体大小
ctx.setFillStyle('#FF5C0F') // 设置字体颜色
ctx.fillText('¥'+that.name, 10*xs, 350*xs)
ctx.setFontSize(20*xs)
ctx.setFillStyle('#000000')
that.textPrewrap(ctx,that.goods.goods_name,10*xs, 380*xs, 22*xs, 280*xs,2)
ctx.setFontSize(12*xs)
ctx.setFillStyle('#7F7F7F')
if(that.num>0){
ctx.fillText('已售: '+that.num, 260*xs, 460*xs)
} else {
ctx.fillText('已售: 0', 260*xs, 460*xs)
}
ctx.setLineDash([4, 1]); // 画虚线
ctx.beginPath();
ctx.moveTo(0,480*xs);
ctx.lineTo(480*xs, 480*xs);
ctx.stroke();
ctx.setFontSize(14*xs)
ctx.setFillStyle('#000000')
ctx.fillText(that.name, 10*xs, 510*xs)
ctx.draw()
},
});
},
// 保存Canvas图片到本地
saveCanvas(){
let that = this;
uni.canvasToTempFilePath({ // 保存canvas为图片
canvasId: 'firstCanvas',
quality: 1,
complete: function(res) {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function() {
console.log('save success');
setTimeout(() => {
}, 2000);
},
fail() {
setTimeout(() => {
}, 1000);
}
});
},
})
}
本文介绍了如何在uni-app中利用canvas进行图形绘制,包括画半圆和整个圆的方法,并提及了uni-app官网提供的canvas绘图指南。同时,文章提到了在小程序中设置downloadFile的图片域名要求,以及将DOM转换为canvas的html2canvas库。此外,推荐了小程序生成海报的painter库和uni-app的painter插件。
1112

被折叠的 条评论
为什么被折叠?



