<canvas canvas-id="canvasId" id="canvas" style="width:300px;height:400px"></canvas>
onReady: function() {
const ctx = wx.createCanvasContext('canvasId');
const query = wx.createSelectorQuery().select('#canvas').boundingClientRect(res => {
ctx.beginPath()
ctx.save()
ctx.moveTo(0, 0)
ctx.lineTo(0, res.height)
ctx.lineTo(res.width, res.height)
ctx.lineTo(res.width, 0)
ctx.setLineWidth(10)
ctx.setStrokeStyle('#f00')
ctx.closePath()
ctx.stroke()
ctx.beginPath()
ctx.restore()
ctx.setFontSize(20)
let str = '1234567891234567891234567891234567891234567891234567891234567891234567891234567891234567891'
this.lineFeed(res, ctx, str)
ctx.draw(true)
}).exec()
}
// 字体换行
lineFeed(res, ctx, str) {
let len = str.length //字体长度
const metrics = ctx.measureText(str[0]).width //字体宽度
// 一行字体的宽度
let ow = Math.floor((res.width-10) / metrics)
//多少列
let lei = Math.ceil(len / ow)
for (let i = 0; i < lei; i++) {
let str1 = ''
str1 = str.slice(i * ow, (i + 1) * ow)
ctx.strokeText(str1, 5, 100 + i * 20)
}
ctx.draw()
},
文本文字,可以自动换行哦!
环切效果
ctx.beginPath()
ctx.arc(100, 100, 10, 0, 2 * Math.PI)
ctx.setFillStyle('#f00')
ctx.fill()
ctx.clip()//相当于css overflow效果
ctx.arc(100, 100, 100, 0, 2 * Math.PI)
ctx.setFillStyle('#ff0')
ctx.fill()
ctx.draw()
微信小程序新接口demo
querycanvas(){
const query = wx.createSelectorQuery()
query.select('#myCanvas')
.fields({ node: true, size: true })
.exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
//const dpr = wx.getSystemInfoSync().pixelRatio //分辨率
const dpr = 750 / getSystemInfoSync.windowWidth
canvas.width = res[0].width * dpr //控制图片 不变形
canvas.height = res[0].height * dpr
ctx.scale(dpr, dpr)
ctx.fillRect(0, 0, 100, 100)
})
},
参考:https://developers.weixin.qq.com/miniprogram/dev/api/canvas/RenderingContext.html
三、使用clearRect函数
var w = theCanvas.width;
var h = theCanvas.height;
context.clearRect(0, 0, w, h);
二、重置画布高度
var w = theCanvas.width;
var h = theCanvas.height;
theCanvas.width = w;
theCanvas.height = h;
使用一个新的背景色简单地填充整个画布,这样就可以清除当前内容
context.fillStyle = '#ffffff';
context.fillRect(0, 0, theCanvas.width, theCanvas.height);