如何用存储在json文件中的不同图像填充节点?

时间:2019-05-26 10:08:03

标签: javascript json d3.js graph

我有一个图,其中每个节点都表示为一个圆。我需要用存储在json文件中的不同图像作为链接来填充它。鉴于节点数量巨大,我需要不会显着降低加载速度的解决方案。

我尝试将图像定义为图案,但是它太昂贵了:( 使用canvas drawImage会更快吗?在这种情况下,如果将图像存储为链接,该如何访问图像?

        var canvas = d3.select("#network"), 
        width = canvas.attr("width"),
        height = canvas.attr("height"),
        r = 7,
        ctx = canvas.node().getContext("2d"),
        simulation = d3.forceSimulation()
            .force("x", d3.forceX(width/2))
            .force("y", d3.forceY(height/2))
            .force("collide", d3.forceCollide(r+1))
            .force("charge", d3.forceManyBody()
                .strength(-20))
            .force("link", d3.forceLink()
                .id(function (d) {return d.id; }));

        d3.json("file.json", function (err, graph) {
            if (err) throw err;

            simulation.nodes(graph.nodes);  
            simulation.force("link")
                .links(graph.links);
            simulation.on("tick", update);                                  

            function update() {
                ctx.clearRect(0,0,width,height);

                ctx.beginPath();        
                graph.links.forEach(drawLink);
                ctx.globalAlpha = 0.5;
                ctx.stroke();       

                ctx.beginPath();
                graph.nodes.forEach(drawNode);
                ctx.globalAlpha = 1.0;
                ctx.fill();
            }
        });         

        function drawNode(d) {              
            ctx.moveTo(d.x, d.y);               
            ctx.arc(d.x, d.y, r, 0, 2*Math.PI);     
        }

        function drawLink(l) {
            ctx.moveTo(l.source.x, l.source.y);
            ctx.lineTo(l.target.x, l.target.y);
        }

json的示例(原始示例有500多个节点)

var graph = {
            nodes:[
                {id: "1", img:"link.img"},
                {id: "2", img:"link.img"},
                {id: "3", img:"link.img"},
                {id: "4", img:"link.img"},
                {id: "5", img:"link.img"},
                {id: "6", img:"link.img"},
                {id: "7", img:"link.img"},
                {id: "8", img:"link.img"},
                {id: "9", img:"link.img"}
            ],
            links: [
                {source: "1", target:"9"},
                {source: "2", target:"9"},
                {source: "3", target:"8"},
                {source: "2", target:"5"},
                {source: "4", target:"2"},
                {source: "2", target:"6"},
                {source: "6", target:"4"},
                {source: "7", target:"8"},
                {source: "5", target:"4"},
                {source: "4", target:"5"},
                {source: "3", target:"6"},
                {source: "7", target:"4"},
                {source: "6", target:"1"},
                {source: "5", target:"1"},
            ]
        };

谢谢你!

0 个答案:

没有答案