AxeSlide软件项目梳理 canvas绘图系列知识点整理
grid类的实现
当鼠标在画布上缩放时,网格能跟着我的鼠标滚动而相应的有放大缩小的效果。
下面是具体实现的代码,draw函数里计算出大网格每条线的间隔和小网格线的间隔,以及大网格和小网格绘制所用的颜色。
具体的实现算法也是参照另外一个软件用到的,但是我们改进了很多,例如控制只将当前画面显示出来的线条绘制出来
draw() {
var scale = (editor && editor.canvas && editor.canvas.canvasImp.scale) || 1;//获取当前画布缩放比
var B = .05;
var t = 50;
for (var e = 50 * scale; e >= 200;) // 放大
{
e /= 4;
t = e / scale;
}
for (; 50 > e;) //缩小
{
e *= 4;
t = e / scale;
}
var i = B + (e - 50) / 150 * (.07 - B);//颜色值 this.clear(0, 0, this.canvasWidth, this.canvasHeight);//清空画布 this.drawGrid(t, i + 0.03);//绘制小格子 this.drawGrid(t * 4, .21 - i);//绘制大格子 }
private drawGrid(e, i) {//e表示每两条线的间隔距离值;i颜色值,大格子的颜色和小格子的颜色值不同
var P = "rgba(0,0,0,";
var l = P + i + ")", t = 0; var scale = (editor && editor.canvas && editor.canvas.canvasImp.scale) || 1;
this.context2D.beginPath();
//为优化性能,控制只绘制当前画面大小的网格线
var b = this.getLimits();
var winInfo = getWindow();
var viewMinx = 0;
var viewMiny = 0;
var viewMaxx = winInfo.width;
var viewMaxy = winInfo.height;
var isDraw = false;
var windowViewPoints = new Common.List<Core.Point>();
windowViewPoints.add(new Core.Point(viewMinx, viewMiny));
windowViewPoints.add(new Core.Point(viewMaxx, viewMaxy));
windowViewPoints.add(new Core.Point(viewMinx, viewMaxy));
windowViewPoints.add(new Core.Point(viewMaxx, viewMiny));
var that = this; var minX = 0, maxX = 0, minY = 0, maxY = 0;//最大、最新 x y值 windowViewPoints.foreach((index, item: Core.Point) => {
var point = that.context2D.transformedPoint(item.x, item.y);
if (index == 0) {
maxX = minX = point.x;
minY = maxY = point.y;
}
else {
minX = minX > point.x ? point.x : minX;
maxX = maxX < point.x ? point.x : maxX; minY = minY > point.y ? point.y : minY;
maxY = maxY < point.y ? point.y : maxY;
}
}); //纵向线条
t = b.minX; while (true) {
if (Math.abs(t - minX) <= e || t >= minX) {
this.context2D.moveTo(t, minY);
this.context2D.lineTo(t, maxY);
}
t = t + e;
if (t >= maxX) break;
} //横向线条
t = b.minY;
while (true) {
if (Math.abs(t - minY) <= e || t >= minY) {
this.context2D.moveTo(minX, t);
this.context2D.lineTo(maxX, t);
}
t = t + e;
if (t >= maxY) break;
}
this.context2D.closePath();
this.context2D.strokeStyle = l;
this.context2D.lineWidth = 1 / scale;
this.context2D.stroke();
}