代码:
<template>
<div class="rect">
<div class="header">
<!-- <el-button type="primary" @click="show">展示</el-button>-->
<!-- <el-button type="success" @click="hide">隐藏</el-button>-->
<el-button type="warning" @click="moveToTop">置顶</el-button>
<el-button type="danger" @click="moveToBottom">置地</el-button>
<el-button type="info" @click="moveUp">上移一层</el-button>
<el-button type="success" @click="moveDown">下移一层</el-button>
</div>
<div id="canvas"></div>
</div>
</template>
<script setup lang="ts">
import {onMounted} from 'vue'
import Konva from 'konva'
let stage:Konva.Stage | null=null
const layer:Konva.Layer=new Konva.Layer()
const group :Konva.Group=new Konva.Group()
onMounted(()=>{
init()
})
const init=()=> {
const el = document.getElementById("canvas")
if (!el) {
return
}
const { clientWidth, clientHeight } = el
//创建一个stage平台
stage = new Konva.Stage({
container: 'canvas',
width: clientWidth,
height: clientHeight,
})
stage.add(layer)
//矩形
group.setAttrs({
x:clientWidth/2,
y:clientHeight/2,
draggable:true
})
const colors=["#ff8800","#ff0000","#ff00ff","#00ffff"]
for (let i=0;i<4;i++){
const rect=new Konva.Rect({
//给图形添加id和名称,方便之后通过id和名称查找图形
id:`rect${i}`,
name:"textName",
x:i * 20,
y:i * 20,
width:100,
height:50,
fill:colors[i],
stroke:'black',
strokeWidth:1,
draggable:true
})
group.add(rect)
}
layer.add(group)
}
const moveToTop=()=>{
if (!stage){
return
}
const shapes=stage.findOne("#rect0")
shapes?.moveToTop()
}
const moveToBottom=()=>{
if (!stage){
return
}
const shapes=stage.findOne("#rect0")
shapes?.moveToBottom()
}
const moveUp=()=>{
if (!stage){
return
}
const shapes=stage.findOne("#rect0")
shapes?.moveUp()
}
const moveDown=()=>{
if (!stage){
return
}
const shapes=stage.findOne("#rect0")
shapes?.moveDown()
}
const show=()=>{
if (!stage){
return
}
// const shapes=stage.findOne("#textId")//通过id查找
// const shapes=stage?.findOne(".textName")//通过名称
const shapes=stage?.findOne("Rect")//通过图形的类别来查找
console.log(shapes)
//设置展示
shapes.show()
}
const hide=()=>{
if (!stage){
return
}
// const shapes=stage.findOne("#textId")//通过id查找
// const shapes=stage?.findOne(".textName")//通过名称
const shapes=stage?.findOne("Rect")//通过图形的类别来查找
console.log(shapes)
//设置展示
shapes.hide()
}
</script>
<style scoped lang="scss">
.rect {
padding: 20px;
.header{
height: 50px;
}
#canvas {
background-color: #eee;
border: 1px solid #666;
height: calc(100vh - 92px);
}
}
</style>