SOURCE

console 命令行工具 X clear

                    
>
console
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>D3 Connect Nodes Across Canvases</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <style>
        #canvas-container {
            display: flex;
        }
        svg {
            border: 1px solid black;
            margin: 10px;
        }
    </style>
</head>
<body>
    <div id="canvas-container">
        <svg id="canvas1" width="300" height="300"></svg>
        <svg id="canvas2" width="300" height="300"></svg>
    </div>
    <script>
        const svg1 = d3.select("#canvas1");
        const svg2 = d3.select("#canvas2");

        // 第一个画布中的节点
        const node1 = svg1.append("circle")
                    .attr("cx", 100)
                    .attr("cy", 150)
                    .attr("r", 20)
                    .attr("fill", "red");

        // 第二个画布中的节点
        const node2 = svg2.append("circle")
                    .attr("cx", 200)
                    .attr("cy", 150)
                    .attr("r", 20)
                    .attr("fill", "blue");

        // 获取节点在文档中的位置
        const node1ScreenCoords = node1.node().getBoundingClientRect();
        const node2ScreenCoords = node2.node().getBoundingClientRect();

        // 计算连线的起点和终点
        const startX = node1ScreenCoords.left + node1ScreenCoords.width / 2;
        const startY = node1ScreenCoords.top + node1ScreenCoords.height / 2;
        const endX = node2ScreenCoords.left + node2ScreenCoords.width / 2;
        const endY = node2ScreenCoords.top + node2ScreenCoords.height / 2;

        // 在文档中添加连线
        d3.select("body").append("svg")
                     .attr("id", "connection")
                     .style("position", "absolute")
                     .style("top", 0)
                     .style("left", 0)
                     .style("width", "100%")
                     .style("height", "100%")
                     .append("line")
                     .attr("x1", startX)
                     .attr("y1", startY)
                     .attr("x2", endX)
                     .attr("y2", endY)
                     .attr("stroke", "black");
    </script>
</body>
</html>