市政項目需展示上海地鐵站點、換乘、線路走向及實時信息流。選用 Qunee for HTML5(輕量 Canvas 圖形組件),快速實現可縮放、可拖拽、站點聯動的線上地鐵圖。
三大實體類型:
{
"labels": [ { "text": "莘莊", "x": 883.591, "y": 1625.695, "rotate": 0.78 } ],
"stations": [ { "id": 5, "x": 869.85, "y": 1597.66, "rotate": 0.785 } ],
"lines": [
{ "name": "1", "color": "#e52035", "stations": [64, 70, 67, ..., { "id": 21, "yOffset": 0.5 }] },
{ "name": "3", "color": "#f9d300", "stations": [6, 95, ..., { "id": 12, "yOffset": 0.5 }] }
]
}
yOffset 處理共線偏移(如 3/4 號線共軌)。function createText(name, x, y, rotate) {
const text = graph.createNode(name, x, y);
if (rotate) text.rotate = rotate;
text.zIndex = 20;
text.image = null;
text.setStyle(Q.Styles.BACKGROUND_COLOR, Q.toColor(0x88FFFFFF));
text.setStyle(Q.Styles.LABEL_ANCHOR_POSITION, Q.Position.LEFT_BOTTOM);
text.setStyle(Q.Styles.LABEL_POSITION, Q.Position.CENTER_MIDDLE);
return text;
}
function createStation(station) {
const node = graph.createNode(null, station.x, station.y);
node.stationId = station.id;
node.setStyle(Q.Styles.LABEL_FONT_SIZE, 10);
node.setStyle(Q.Styles.LABEL_ANCHOR_POSITION, Q.Position.CENTER_MIDDLE);
node.zIndex = 10;
if (station.rotate) {
node.image = roundRect; node.rotate = station.rotate;
} else { node.image = circle; }
node.setStyle(Q.Styles.SHAPE_FILL_COLOR, "#FFF");
node.setStyle(Q.Styles.SHAPE_STROKE_STYLE, "#000");
return node;
}
function createLine(line) {
const node = graph.createNode(line.name);
node.stations = line.stations;
node.movable = false;
node.setStyle(Q.Styles.LABEL_FONT_SIZE, 50);
node.setStyle(Q.Styles.LABEL_COLOR, line.color);
node.setStyle(Q.Styles.LAYOUT_BY_PATH, true);
node.setStyle(Q.Styles.SHAPE_STROKE, size);
node.setStyle(Q.Styles.SHAPE_STROKE_STYLE, line.color);
updateLine(node, true);
return node;
}
function updateLine(line, addListener) {
const path = new Q.Path();
line.image = path;
let first = true;
Q.forEach(line.stations, s => {
const station = getStation(s.id || s);
if (!station) return;
if (addListener) addLocationChangeListener(station.stationId, line);
let {x, y} = station.location;
if (s.yOffset) {
const offset = s.yOffset * size;
const rotate = station.rotate || 0;
x += Math.cos(rotate) * offset;
y += Math.sin(rotate) * offset;
}
first ? path.moveTo(x, y) : path.lineTo(x, y);
first = false;
});
}
graph.interactionDispatcher.addListener(evt => {
if (evt.kind !== Q.InteractionEvent.ELEMENT_MOVING) return;
Q.forEach(evt.datas, data => {
if (!data.stationId) return;
const listeners = stationLocationChangeListeners[data.stationId];
if (listeners) for (const l in listeners) updateLine(listeners[l]);
});
});
若不依賴 Qunee,可用 D3.js + SVG 或 Canvas 原生 API 實現同樣邏輯:數據結構不變,渲染層替換即可。核心難點在路徑幾何計算與拖拽聯動機制,而非具體庫。