小程序绘制图片
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this
//获取用户设备信息,屏幕宽度
wx.getSystemInfo({
success: res => {
//设置画图信息
var unit = res.screenWidth / 375
var path1 = "../../images/bj.png"
var unlight = "../../images/bt.png"
var wxappName = "来试试运气"
var ctx = wx.createCanvasContext('share')
ctx.drawImage(path1, 0, 0, unit * 375, unit * 462.5)
ctx.drawImage(unlight, unit * 274, unit * 240, unit * 22, unit * 32)
ctx.drawImage(unlight, unit * 20, unit * 385, unit * 55, unit * 55)
ctx.setFontSize(14)
ctx.setFillStyle("#fff")
ctx.fillText("长按识别小程序", unit * 90, unit * 408)
ctx.fillText(wxappName, unit * 90, unit * 428)
ctx.draw(false, function () {
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: unit * 375,
height: unit * 462.5,
//设置图片大小
destWidth: unit * 375 * 2,
destHeight: unit * 462.5 * 2,
canvasId: 'share',
success: function (res) {
//画板路径保存成功后,调用方法吧图片保存到用户相册
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: (res) => {
console.log('保存相册成功')
},
fail: (err) => {
console.log('保存相册失败')
}
})
}
})
});
//绘制填充一个矩形
ctx.setFillStyle('red')
ctx.fillRect(10, 10, 150, 100)
ctx.draw(true)
//绘制边框一个矩形
ctx.setStrokeStyle('white')
ctx.strokeRect(2, 150, 150, 150)
ctx.draw(true)
//绘制一个三角形
ctx.moveTo(10, 10)
ctx.lineTo(100, 10)
ctx.lineTo(100, 100)
ctx.setFillStyle('yellow')
ctx.fill()
ctx.draw(true)
//获取文字宽度
var fst = 'italic bold 20px cursive'
ctx.font = fst
const metrics = ctx.measureText(fst)
ctx.fillText(fst, 0, 100)
ctx.draw(true)
console.log(metrics.width)
//绘制一根线条
ctx.moveTo(10, 50)
ctx.lineTo(100, 50)
ctx.stroke()
ctx.draw(true)
//设置阴影
ctx.setFillStyle('red')
ctx.setShadow(2, 20, 20, 'black')
ctx.fillRect(200, 200, 150, 75)
ctx.draw(true)
//虚线
ctx.setLineDash([1, 2], 5);
ctx.beginPath();
ctx.moveTo(0, 100);
ctx.lineTo(400, 100);
ctx.stroke();
ctx.draw(true)
//两头半圆的线条
ctx.beginPath()
ctx.setLineCap('round')
ctx.setLineWidth(30)
ctx.moveTo(30, 50)
ctx.lineTo(150, 50)
ctx.stroke()
ctx.draw(true)
//透明度
ctx.setGlobalAlpha(0.2)
ctx.setFillStyle('yellow')
ctx.fillRect(100, 250, 150, 100)
ctx.draw(true)
}
})
},