有時候咱們先在畫布上畫一個表格相似一下設計軟件那種。一方面做爲參考線,一方面給人一直專業的趕腳。。。canvas
先貼上一段網上(不是我寫的)能夠運行的代碼 https://codepen.io/rodan8888/pen/eBWNdp設計
經過這個代碼提供了咱們一個思路,即橫着畫完,豎着畫,每一個五行變個色。可是實際應用中咱們不可能這麼簡單的就能完成,考慮到畫布的大小是不規則的,畫布的zoom是變化的,如何根據後續其餘畫布刷新grid,清空grid還須要一些操做。code
// 首先根據畫布的大小計算分十大個格子, let dis = state.pannelW / 50 let oneDis = dis * 5 // 要讓grid不能夠選中selectable,不能夠有事件觸發evented,不能夠輸出excludeFromExport let options = { distance: dis, width: state.canvas.width / state.zoom + oneDis, height: state.canvas.height / state.zoom + oneDis, param: { stroke: '#ebebeb', strokeWidth: 1, hoverCursor: 'default', selectable: false, evented: false, excludeFromExport: true, hasControls: false, perPixelTargetFind: false, } } let gridLen = options.width / options.distance; let lines = []; for (let i = 0; i < gridLen; i++) { let distance = i * options.distance, horizontal = new fabric.Line([distance, 0, distance, options.width], options.param), vertical = new fabric.Line([0, distance, options.width, distance], options.param); if (i % 5 === 0) { horizontal.set({ stroke: '#cccccc' }); vertical.set({ stroke: '#cccccc' }); } lines.push(horizontal) lines.push(vertical) } let _left = state.arrX[0] > oneDis ? state.arrX[0] % oneDis - oneDis : state.arrX[0] - oneDis let _top = state.arrY[0] > oneDis ? state.arrY[0] % oneDis - oneDis : state.arrY[0] - oneDis //定義好以後放到一個group裏面 state.groupLines = new fabric.Group(lines, { selectable: false, lockMovementX: true, lockMovementY: true, lockRotation: true, lockScalingX: true, lockScalingY: true, lockUniScaling: true, hoverCursor: 'auto', name: 'grid', left: _left, top: _top, evented: false, }); state.canvas.add(state.groupLines); state.canvas.sendToBack(state.groupLines);
這個地方我定義了一個group放在操做的樹(或者全局變量)中,這樣其餘地方能夠對grid進行操做。好比zoom的時候直接remove掉從新繪製。blog
最後補充一個小功能吧,自動對齊,在一些簡單嚴格的設計需求中,可能須要自動對齊表格參考線。緊接着上面的代碼,添加一個move和modified的事件監聽。事件
let onLeft = dis - state.arrX[0] % dis let onTop = dis - state.arrY[0] % dis state.canvas.off('object:moved') state.canvas.off('object:modified') state.canvas.on('object:moved', function(options) { options.target.set({ left: Math.round(options.target.left / dis) * dis - onLeft + dis, top: Math.round(options.target.top / dis) * dis - onTop + dis }); options.target.setCoords(); }); state.canvas.on('object:modified', function(options) { let newWidth = (Math.round(options.target.getScaledWidth() / dis)) * dis; let newHeight = (Math.round(options.target.getScaledHeight() / dis)) * dis; options.target.set({ left: Math.round(options.target.left / dis) * dis - onLeft + dis, top: Math.round(options.target.top / dis) * dis - onTop + dis, width: newWidth, height: newHeight, scaleX: 1, scaleY: 1 }); options.target.setCoords(); });
到此表格就完成了。rem