UniApp在微信小程序中的Canvas画布操作
-
画布建立
<canvas
canvas-id="posterid"
style="width:300rpx;height:400rpx;"
disable-scroll="true"
@touchstart=""
@touchmove=""
@touchend=""
>
</canvas>
var ctx = uni.createCanvasContext('posterid')
ctx.draw();
-
网络图片在画布中需要先下载到本地才可以绘入画布中,最后导出图片
-
下载网络图片(这一步要先准备好) uni.downloadFile({
url: imgUrl,
success: (res) => {
if (res.statusCode === 200) {
uni.setStorageSync('headImg',res.tempFilePath);
}
},fail: (err) => {
console.log(err);
}
})
-
先确认是否可以获取到网络图片下载到本地后的信息才可以开始绘画
-
获取图片信息 getImageInfo(image) {
return new Promise((req, rej) => {
uni.getImageInfo({
src: image,
success: function(res) {
req(res)
},
});
})
}
-
绘制的几个方法
-
文本换行
ctb (ctx,text,x,y,w,fontStyle) {
ctx.save();
ctx.fillStyle = fontStyle.fillStyle;
ctx.textAlign = fontStyle.textAlign;
ctx.textBaseline = fontStyle.textBaseline;
const chr = text.split('');
const row = [];
let temp = '';
for (let a = 0; a < chr.length; a++) {
if (ctx.measureText(temp).width < w) { } else {
if (/[,。!》]/im.test(chr[a])) {
temp += ` ${chr[a]}`;
a++;
}
if (/[《]/im.test(chr[a - 1])) {
temp = temp.substr(0, temp.length - 1);
a--;
}
row.push(temp);
temp = '';
}
temp += chr[a] ? chr[a] : '';
}
row.push(temp);
for (let b = 0; b < row.length; b++) {
ctx.fillText(row[b], x, y + b * fontStyle.lineHeight);
}
}
-
矩形图片裁剪成原型
drawCircular(ctx,width, height, x, y, url) {
var avatarurl_width = width;
var avatarurl_heigth = height;
var avatarurl_x = x;
var avatarurl_y = y;
ctx.save();
ctx.beginPath();
ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
ctx.clip();
ctx.drawImage(url, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth);
ctx.restore();
}
-
绘画需要异步执行
async draw(){
var ctx = uni.createCanvasContext('posterid')
let headImg = await this.getImageInfo(uni.getStorageSync("headImg"));
setTimeout(() =>{
ctx.draw(false,() =>{
setTimeout(() =>{
uni.canvasToTempFilePath({
canvasId: 'posterid',
destWidth: this.cropW * this.canvasScale * 5,
destHeight: this.cropH * this.canvasScale * 5,
quality:1,
fileType:'png',
success: (res) => {
if(res.errMsg == "canvasToTempFilePath:ok"){
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success:(res) => {
uni.showToast({
icon: 'none',
position: 'bottom',
title: "图片已下载至【图库】,请打开【图库】查看",
});
},fail: (err) => {
if(err.errMsg === "saveImageToPhotosAlbum:fail auth deny"){
uni.showModal({
title: '提示',
content: '需要您授权保存相册',
showCancel: false,
success(res) {
if (res.confirm) {
uni.openSetting({
success(settingdata) {
if (settingdata.authSetting['scope.writePhotosAlbum']) {
uni.showModal({
title: '提示',
content: '获取权限成功,再次保存图片即可成功',
showCancel: false,
})
} else {
uni.showModal({
title: '提示',
content: '获取权限失败,无法保存到相册',
showCancel: false
})
}
}
})
}
}
})
}else{
uni.showToast({
icon: 'none',
title: '下载失败',
});
}
}
});
}
},
}, this);
},500)
})
},1500)
}
|