HOW - Canvas 入门系列之基于vue-konva的多维表格
<template>
<v-stage ref="stage" :config="stageSize" @wheel="handleWheel">
<!-- 其他代码省略 -->
<v-layer>
<v-rect
v-for="(cell, index) in visibleCells"
:key="index"
:config="cellConfig(cell)"
/>
</v-layer>
</v-stage>
</template>
<script>
export default {
data() {
return {
// 其他数据定义省略
visibleCells: [], // 可见的单元格数组
};
},
methods: {
// 其他方法定义省略
cellConfig(cell) {
const x = (cell.col - this.startCol) * this.cellSize;
const y = (cell.row - this.startRow) * this.cellSize;
return {
x,
y,
width: this.cellSize,
height: this.cellSize,
fill: this.getCellColor(cell),
stroke: 'black',
strokeWidth: 1,
};
},
getCellColor(cell) {
// 根据cell的值返回不同的颜色
if (cell.value === 0) {
return 'white';
}
return this.colorMap[cell.value];
},
handleWheel(e) {
e.evt.preventDefault();
const scaleBy = 1.2;
const oldScale = this.scale;
const newScale = e.evt.deltaY < 0 ? oldScale * scaleBy : oldScale / scaleBy;
if (newScale >= this.minScale && newScale <= this.maxScale) {
this.scale = newScale;
this.updateVisibleCells();
const stage = this.$refs.stage.getStage();
const pointer = stage.getContainer().getPointerPosition();
const dx = pointer.x - this.$refs.stage.getStage().getWidth() / 2;
const dy = pointer.y - this.$refs.stage.getStage().getHeight() / 2;
stage.position({ x: dx, y: dy });
}
},
updateVisibleCells() {
const cols = this.puzzle.cols;
const rows = this.puzzle.rows;
const startCol = Math.max(0, Math.floor(this.startCol));
const startRow = Math.max(0, Math.floor(this.startRow));
const endCol = startCol + cols - 1;
const endRow = startRow + rows - 1;
this.visibleCells = this.puzzle.cells
.filter(cell => cell.row >= startRow && cell.row <= endRow &&
cell.col >= startCol && cell.col <= endCol);
}
},
watch: {
scale: 'updateVisibleCells',
},
mounted() {
this.updateVisibleCells();
}
};
</script>
在这个代码实例中,我们使用了Vue.js和vue-konva库来创建一个可缩放的电子表
评论已关闭