公司最近提了个新需求,就是要在canvas画板上要画许多条线,点击那条线就删除那条线的功能,刚开始我用的原生canvas,很麻烦并不容易实现。于是改变思路,用到了'KonvaJS'
1、KonvaJS 是一个功能强大的Html5 Canvas库。
文档:https://konvajs.org/docs/vue/index.html
npm install vue-konva@2 konva --save
2、引用
在main.js中
import VueKonva from 'vue-konva'; Vue.use(VueKonva);
3、使用
<div id="box_img">//获取画布的宽高 let box = document.getElementById("box_img"); let width = box.offsetWidth; let height = box.offsetHeight; this.chartWidth = box.offsetWidth; this.chartHeight = box.offsetHeight;
<v-stage class="palette" id="canvas" ref="canvas" :config="{ width: chartWidth, height: chartHeight }" //动态获取的canvas宽高 @mousedown="stageMousedown" @mousemove="stageMousemove" @mouseup="stageMouseup" > <v-layer> <v-line v-for="(item, index) in lines" :config="item" @click="lineDel(index)" /> </v-layer> </v-stage>
<div>
<div @click='ftchEraser'>橡皮</div>
4、js部分
ftchEraser() { this.isEraser = !this.isEraser; },stageMousedown() {this.isPaint = true; const stage = this.$refs.canvas.getStage(); const pos = stage.getPointerPosition(); this.lines.push({ //存到一个空数组中把数据 stroke: "red", strokeWidth: 2, //这块设置线条颜色、粗细 points: [pos.x, pos.y], }); }, stageMousemove() { if (!this.isPaint) { return; } const stage = this.$refs.canvas.getStage(); const pos = stage.getPointerPosition(); const lastLine = this.lines[this.lines.length === 1 ? 0 : this.lines.length - 1]; const newPoints = lastLine.points.concat([pos.x, pos.y]); lastLine.points = newPoints; }, stageMouseup() { this.isPaint = false; this.lines = this.lines.filter((item) => item.points.length !== 2); }, lineDel(index) { if (this.isEraser) { this.lines.splice(index, 1); //这块点击线条删除部分 } },
标签:box,canvas,vue,const,那条,lines,pos From: https://www.cnblogs.com/haiyang-/p/17095310.html