软件项目技术点(5)——在canvas上绘制动态网格线
AxeSlide软件项目梳理 canvas绘图系列知识点整理
grid类的实现
当鼠标在画布上缩放时,网格能跟着我的鼠标滚动而相应的有放大缩小的效果。
下面是具体实现的代码,draw函数里计算出大网格每条线的间隔和小网格线的间隔,以及大网格和小网格绘制所用的颜色。
具体的实现算法也是参照另外一个软件用到的,但是我们改进了很多,例如控制只将当前画面显示出来的线条绘制出来
1 draw() { 2 var scale = (editor && editor.canvas && editor.canvas.canvasImp.scale) || 1;//获取当前画布缩放比 3 var B = .05; 4 var t = 50; 5 for (var e = 50 * scale; e >= 200;) // 放大 6 { 7 e /= 4; 8 t = e / scale; 9 } 10 for (; 50 > e;) //缩小 11 { 12 e *= 4; 13 t = e / scale; 14 } 15 var i = B + (e - 50) / 150 * (.07 - B);//颜色值 16 17 this.clear(0, 0, this.canvasWidth, this.canvasHeight);//清空画布 18 19 this.drawGrid(t, i + 0.03);//绘制小格子 20 21 this.drawGrid(t * 4, .21 - i);//绘制大格子 22 23 }
1 private drawGrid(e, i) {//e表示每两条线的间隔距离值;i颜色值,大格子的颜色和小格子的颜色值不同 2 var P = "rgba(0,0,0,"; 3 var l = P + i + ")", t = 0; 4 5 var scale = (editor && editor.canvas && editor.canvas.canvasImp.scale) || 1; 6 this.context2D.beginPath(); 7 //为优化性能,控制只绘制当前画面大小的网格线 8 var b = this.getLimits(); 9 var winInfo = getWindow(); 10 var viewMinx = 0; 11 var viewMiny = 0; 12 var viewMaxx = winInfo.width; 13 var viewMaxy = winInfo.height; 14 var isDraw = false; 15 var windowViewPoints = new Common.List<Core.Point>(); 16 windowViewPoints.add(new Core.Point(viewMinx, viewMiny)); 17 windowViewPoints.add(new Core.Point(viewMaxx, viewMaxy)); 18 windowViewPoints.add(new Core.Point(viewMinx, viewMaxy)); 19 windowViewPoints.add(new Core.Point(viewMaxx, viewMiny)); 20 var that = this; 21 22 var minX = 0, maxX = 0, minY = 0, maxY = 0;//最大、最新 x y值 23 24 windowViewPoints.foreach((index, item: Core.Point) => { 25 var point = that.context2D.transformedPoint(item.x, item.y); 26 if (index == 0) { 27 maxX = minX = point.x; 28 minY = maxY = point.y; 29 } 30 else { 31 minX = minX > point.x ? point.x : minX; 32 maxX = maxX < point.x ? point.x : maxX; 33 34 minY = minY > point.y ? point.y : minY; 35 maxY = maxY < point.y ? point.y : maxY; 36 } 37 }); 38 39 //纵向线条 40 t = b.minX; 41 42 while (true) { 43 if (Math.abs(t - minX) <= e || t >= minX) { 44 this.context2D.moveTo(t, minY); 45 this.context2D.lineTo(t, maxY); 46 } 47 t = t + e; 48 if (t >= maxX) break; 49 } 50 51 52 //横向线条 53 t = b.minY; 54 while (true) { 55 if (Math.abs(t - minY) <= e || t >= minY) { 56 this.context2D.moveTo(minX, t); 57 this.context2D.lineTo(maxX, t); 58 } 59 t = t + e; 60 if (t >= maxY) break; 61 } 62 this.context2D.closePath(); 63 this.context2D.strokeStyle = l; 64 this.context2D.lineWidth = 1 / scale; 65 this.context2D.stroke(); 66 }