微信小程序画布绘制
生成上下文
ctx = wx.createCanvasContext('canvasID');
对应的节点信息
<canvas canvas-id="canvasID"
class="canvas-one"
style="width:{
{
width}}px;height:{
{
height}}px">
</canvas>
获取对应的手机屏幕的大小
wx.getSystemInfo({
success: res => {
rpx = res.windowWidth/375; // 像素比/iPhone6大小
this.setData({
width: res.windowWidth,
height: res.windowHeight
})
}
})
canvas 是在一个二维的网格当中,左上角的坐标为(0, 0)
网络图片在画布中不显示的,所以要这样操作,转换成临时图片
wx.getImageInfo({
src: img,
success: res => {
this.setData({
img: res.path
})
}
});
... ctx.drawImage(img, 0, 0, 150, 100);
绘制图像,drawImage,绘制图像,图像保持原始尺寸,参数: 路径,x 坐标,y 坐标,宽度,高度
ctx.drawImage(path, 0, 0, 150, 100);
填充画布背景色, 填充坐标 (x, y, with, height)
ctx.setFillStyle('#f6f6f6');
ctx.fillRect(0*rpx, 0*rpx, width, height);
绘制文字及大小
ctx.setFontSize(15*rpx);
ctx.fillStyle = "#666";
ctx.fillText("字体", 24*rpx, 341*rpx);
metrics测量文本尺寸信息,目前仅返回文本宽度
const metrics = ctx.measureText('Hello World');
console.log(metrics.width);
导出图片
导出图片,把当前画布指定区域的内容导出生成指定大小的图片,并返回文件路径
wx.canvasToTempFilePath({
x: 100,
y: 200,
width: 50,
height: 50,
destWidth: 100,
destHeight: 100,
canvasId: 'myCanvas',
success: function(res) {
console.log(res.tempFilePath)
}
})
保存图片
saveCanvas: function(){
wx.showLoading({
title: '海报生成中'});
setTimeout(() => {
wx.hideLoading();
wx.canvasToTempFilePath({
x: 0,
y: 0,
canvasId: 'canvasID',
fileType: 'png',
success: res => {
let url = res.tempFilePath;
wx.getSetting({
//询问用户是否保存相册到本地
success: set => {
if (set.authSetting['scope.writePhotosAlbum']) {
wx.saveImageToPhotosAlbum({
filePath: url,
success: (res) => {
Tools.$Toast('海报已为您保本地');
}
})
} else {
Tools.$Toast('保存失败!请开启访问手机相册权限');
wx.authorize({
scope: 'scope.writePhotosAlbum',
success: res => {
wx.saveImageToPhotosAlbum({
filePath: url,
success: (res) => {
Tools.$Toast('海报已为您保本地');
}
})
},
fail: res => {
wx.showModal({
title: '保存失败',
content: '请开启访问手机相册权限',
success(res) {
if (res.confirm){
wx.openSetting(); // 无效
}
}
})
}
})
}
}
})
},
fail: function (res) {
Tools.$Toast('海报获取失败');
}
})
}, 600);
},