生活随笔
收集整理的這篇文章主要介紹了
鼠标移动框选动态绘制图形,基于zrender
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
本文只介紹根據(jù)鼠標(biāo)事件動態(tài)繪制矩形方法
zrender實現(xiàn)簡易畫板功能可繪制大部分常用圖形在文章末尾可參考
像下圖這樣,可隨心所欲繪制你想繪制的矩形:
完整代碼:(有詳細(xì)注釋,有任何疑問歡迎留言)
<template><div class="zrender"><div id="zrender-canvas"></div></div>
</template><script>
import zrender from 'zrender'
export default {name: 'zrender',data() {return {zr: null,group: null,currentId: null}},created() {},mounted() {this.init()},methods: {init() {this.zr = zrender.init(document.getElementById('zrender-canvas'))this.group = new zrender.Group()this.zr.add(this.group)this.handleMouse()},handleMouse() {// 設(shè)置三個變量flag鼠標(biāo)按下標(biāo)志、起點坐標(biāo)組、終點坐標(biāo)組let flag = falselet startPos = nulllet endPos = null// 給畫布添加鼠標(biāo)事件this.zr.on('mousedown', e => {// 鼠標(biāo)按下,獲取按下的坐標(biāo)點flag = truestartPos = [e.event.zrX, e.event.zrY]})this.zr.on('mousemove', e => {// 鼠標(biāo)移動時if (!flag) return false// 在鼠標(biāo)按下的情況下執(zhí)行以下操作// 獲取鼠標(biāo)移動的坐標(biāo)點endPos = [e.event.zrX, e.event.zrY]// group遍歷所有子節(jié)點移除當(dāng)前id對應(yīng)的元素(此處可跳過先看下文)this.group.eachChild(el => {if (el.id === this.currentId) {this.group.remove(el)}})// 創(chuàng)建一個圓矩形let rect = new zrender.Rect({shape: {x: startPos[0], // 起點橫坐標(biāo)y: startPos[1], // 起點縱坐標(biāo)width: endPos[0] - startPos[0], // 寬height: endPos[1] - startPos[1] // 高},style: {fill: 'transparent', // 填充顏色,默認(rèn)#000stroke: '#000', // 描邊顏色,默認(rèn)nulllineWidth: 1 // 線寬, 默認(rèn)1}})// 每一個new出來的實例都有一個自己的id,賦值給currentId// 確保鼠標(biāo)移動過程中不停的new,同時再移除掉this.currentId = rect.id// 添加圓到group里this.group.add(rect)})this.zr.on('mouseup', e => {// 鼠標(biāo)抬起的時候,把最后一次賦值的id清空掉,保證畫布上可以留下鼠標(biāo)事件中最后一個new的實例this.currentId = nullflag = false})}}
}
</script><style>
#zrender-canvas {height:700px;
}
</style>
如下圖簡易畫板功能可繪制大部分漂亮的圖形,可保存圖片到本地
參考:https://gitlab.com/zhangcw66/draw_board
說明:畫板功能并不嚴(yán)謹(jǐn),可參考學(xué)習(xí)繪圖,不建議實際使用
總結(jié)
以上是生活随笔為你收集整理的鼠标移动框选动态绘制图形,基于zrender的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。