JSFiddle - React, Tailwind, and code Playground

by Rajesh Danabal

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Downward Directed Graph with D3 and Canvas</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f4f4f4;
        }
    </style>
</head>
<body>
    <canvas id="graphCanvas" width="600" height="400"></canvas>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const canvas = document.getElementById("graphCanvas");
            const context = canvas.getContext("2d");
            const width = canvas.width;
            const height = canvas.height;

            // Sample graph data
            const nodes = [
                { id: "A" },
                { id: "B" },
                { id: "C" },
                { id: "D" },
                { id: "E" },
                { id: "F" }
            ];

            const links = [
                { source: "A", target: "B" },
                { source: "A", target: "C" },
                { source: "B", target: "D" },
                { source: "B", target: "E" },
                { source: "C", target: "F" }
            ];

            // Create force simulation
            const simulation = d3
                .forceSimulation(nodes)
                .force("link", d3.forceLink(links).id(d => d.id).distance(80))
                .force("charge", d3.forceManyBody().strength(-200))
                .force("center", d3.forceCenter(width / 2, 50)) // Start at the top
                .force("y", d3.forceY().strength(0.1)) // Encourage downward flow
                .on("tick", () => {
                    context.clearRect(0, 0, width, height);

                    // Draw links
                   ...