微信小程序canvas绘制表格根据input每输入一次自动添加行内内容
要实现根据输入自动添加行内内容的功能,你需要以下步骤:
- 在wxml文件中添加一个canvas组件和一个input组件,用于绘制表格和输入内容。
<canvas canvas-id="myCanvas"></canvas>
<input bindinput="onInput" />
- 在对应的js文件中,获取canvas的上下文对象和输入内容。
Page({
data: {
content: '', // 输入内容
rows: [] // 行内内容数组
},
onInput(e) {
this.setData({
content: e.detail.value
});
},
onReady() {
const ctx = wx.createCanvasContext('myCanvas');
this.setData({
ctx: ctx
});
}
})
- 在onInput方法中,将输入内容添加到行内内容数组中,并调用绘制表格的方法。
onInput(e) {
this.setData({
content: e.detail.value
});
this.drawTable();
},
drawTable() {
const ctx = this.data.ctx;
const rows = this.data.rows;
// 绘制表格的代码
ctx.draw();
}
- 在绘制表格的代码中,遍历行内内容数组,并根据每个内容绘制一行表格。
drawTable() {
const ctx = this.data.ctx;
const rows = this.data.rows;
// 绘制表格的代码
// 清空画布
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// 绘制表头
ctx.fillText('表头', cellWidth / 2, lineHeight);
// 绘制行内内容
for (let i = 0; i < rows.length; i++) {
ctx.fillText(rows[i], cellWidth / 2, (i + 2) * lineHeight);
}
ctx.draw();
}
- 在onReady方法中调用绘制表格的方法,初始化表格。
onReady() {
const ctx = wx.createCanvasContext('myCanvas');
this.setData({
ctx: ctx
});
this.drawTable();
}
- 在onInput方法中,将输入内容添加到行内内容数组中,并调用绘制表格的方法。
onInput(e) {
this.setData({
content: e.detail.value
});
this.data.rows.push(e.detail.value);
this.drawTable();
}
这样当每次输入内容时,会自动添加到行内内容数组中,并绘制表格显示出来
原文地址: https://www.cveoy.top/t/topic/h8uj 著作权归作者所有。请勿转载和采集!