| 26 | const nodeSize = 6; |
| 27 | |
| 28 | function drawGraph(graph, layout) { |
| 29 | let parent = (window.__sandbox ? window.__sandbox.output.div : document.body); |
| 30 | let canvas = parent.querySelector("canvas"); |
| 31 | if (!canvas) { |
| 32 | canvas = parent.appendChild(document.createElement("canvas")); |
| 33 | canvas.width = canvas.height = 400; |
| 34 | } |
| 35 | let cx = canvas.getContext("2d"); |
| 36 | |
| 37 | cx.clearRect(0, 0, canvas.width, canvas.height); |
| 38 | let scale = new Scale(layout, canvas.width, canvas.height); |
| 39 | |
| 40 | // Draw the edges. |
| 41 | cx.strokeStyle = "orange"; |
| 42 | cx.lineWidth = 3; |
| 43 | for (let i = 0; i < layout.length; i++) { |
| 44 | let conn = graph.neighbors(i); |
| 45 | for (let target of conn) { |
| 46 | if (conn <= i) continue; |
| 47 | cx.beginPath(); |
| 48 | cx.moveTo(scale.x(layout[i].x), scale.y(layout[i].y)); |
| 49 | cx.lineTo(scale.x(layout[target].x), scale.y(layout[target].y)); |
| 50 | cx.stroke(); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | // Draw the nodes. |
| 55 | cx.fillStyle = "purple"; |
| 56 | for (let pos of layout) { |
| 57 | cx.beginPath(); |
| 58 | cx.arc(scale.x(pos.x), scale.y(pos.y), nodeSize, 0, 7); |
| 59 | cx.fill(); |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | // The function starts by drawing the edges, so that they appear |
| 64 | // behind the nodes. Since the nodes on _both_ side of an edge refer |