[D3] Add image to the node

We can create node with 'g' container, then append 'image' to the nodes.

            // Create container for the images
            const svgNodes = svg
                .append('g')
                .attr('class', 'nodes')
                .selectAll('circle')
                .data(d3.values(nodes))
                .enter().append('g');

            // Add image to the nodes
            svgNodes
                .append('image')
                .attr('xlink:href', d => `/static/media/${d.name.toLowerCase()}.png`)
                .attr('x', -25)
                .attr('y', -25)
                .attr('height', 50)
                .attr('width', 50);

Then on each 'tick', we need to position the nodes:

            simulation
                .nodes(d3.values(nodes))
                .on('tick', ticked);

            function dragstarted(d) {
                if (!d3.event.active) simulation.alphaTarget(0.3).restart();
                d.fx = d.x;
                d.fy = d.y;
            }

            function dragged(d) {
                d.fx = d3.event.x;
                d.fy = d3.event.y;
            }

            function dragended(d) {
                if (!d3.event.active) simulation.alphaTarget(0);
                d.fx = null;
                d.fy = null;
            }

            function ticked() {
                svgNodes
                    .attr('transform', d =>`translate(${d.x},${d.y})`)
                    .call(d3.drag()
                        .on('start', dragstarted)
                        .on('drag', dragged)
                        .on('end', dragended));

            }
原文地址:https://www.cnblogs.com/Answer1215/p/7487863.html