?js画图开发库--mxgraph--[grid-网格.html]?
?
点击图形下方按钮:网格根据图形大小变化:
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]--> <!DOCTYPE html> <html> <head> <meta http-equiv=Content-Type content="text/html;charset=utf-8"> <title>Grid example for mxGraph</title> <!-- 如果本文件的包与src不是在同一个目录,就要将basepath设置到src目录下 --> <script type="text/javascript"> mxBasePath = '../src'; </script> <!-- 引入支持库文件 --> <script type="text/javascript" src="../src/js/mxClient.js"></script> <!-- 示例代码 --> <script type="text/javascript"> //程序在此启动 function main(container) { // // 检测浏览器兼容性 if (!mxClient.isBrowserSupported()) { mxUtils.error('Browser is not supported!', 200, false); } else { mxEvent.disableContextMenu(document.body); //去锯齿效果 mxRectangleShape.prototype.crisp = true; // 在容器中创建图形 var graph = new mxGraph(container); graph.graphHandler.scaleGrid = true; graph.setPanning(true); // 默认右键下拉列表 new mxRubberband(graph); // 动态地创建网格(需要画布) (function() { try { var canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = '0px'; canvas.style.left = '0px'; canvas.style.zIndex = -1; graph.container.appendChild(canvas); var ctx = canvas.getContext('2d'); // 过滤画布事件,修改画布作为容器 mxGraphViewIsContainerEvent = mxGraphView.prototype.isContainerEvent; mxGraphView.prototype.isContainerEvent = function(evt) { return mxGraphViewIsContainerEvent.apply(this, arguments) || mxEvent.getSource(evt) == canvas; }; var s = 0; var gs = 0; var tr = new mxPoint(); var w = 0; var h = 0; function repaintGrid() { if (ctx != null) { var bounds = graph.getGraphBounds(); var width = Math.max(bounds.x + bounds.width, graph.container.clientWidth); var height = Math.max(bounds.y + bounds.height, graph.container.clientHeight); var sizeChanged = width != w || height != h; if (graph.view.scale != s || graph.view.translate.x != tr.x || graph.view.translate.y != tr.y || gs != graph.gridSize || sizeChanged) { tr = graph.view.translate.clone(); s = graph.view.scale; gs = graph.gridSize; w = width; h = height; // 根据需要清除背景 if (!sizeChanged) { ctx.clearRect(0, 0, w, h); } else { canvas.setAttribute('width', w); canvas.setAttribute('height', h); } var tx = tr.x * s; var ty = tr.y * s; // 设定网格线的距离(以像素为单位) var minStepping = graph.gridSize; var stepping = minStepping * s; if (stepping < minStepping) { var count = Math.round(Math.ceil(minStepping / stepping) / 2) * 2; stepping = count * stepping; } var xs = Math.floor((0 - tx) / stepping) * stepping + tx; var xe = Math.ceil(w / stepping) * stepping; var ys = Math.floor((0 - ty) / stepping) * stepping + ty; var ye = Math.ceil(h / stepping) * stepping; xe += Math.ceil(stepping); ye += Math.ceil(stepping); var ixs = Math.round(xs); var ixe = Math.round(xe); var iys = Math.round(ys); var iye = Math.round(ye); // 绘制网格 ctx.strokeStyle = '#f6f6f6'; ctx.beginPath(); for (var x = xs; x <= xe; x += stepping) { x = Math.round((x - tx) / stepping) * stepping + tx;