vasturiano / react-force-graph

React component for 2D, 3D, VR and AR force directed graphs
https://vasturiano.github.io/react-force-graph/example/large-graph/
MIT License
2.17k stars 277 forks source link

Setting an image in the background #321

Open diegozuro opened 2 years ago

diegozuro commented 2 years ago

Hi @vasturiano, I wanted to know if there is a way to set a personal image to be used as the "backgroundColor" feature.

Thank you very much!

JonThom commented 2 years ago

@diegozuro I achieved it using the onRenderFramePre argument:


    const onRenderFramePre = (ctx, globalScale) => {
        const centreCoordinates = {"x":250, "y":250}
        const backgroundImg = new Image();
        backgroundImg.src = "www.my-image-url.com";
        ctx.drawImage(backgroundImg, centreCoordinates.x - backgroundImg.width / 2, centreCoordinates.y - backgroundImg.height / 2);
    };
diegozuro commented 2 years ago

Thanks for your answer @JonThom. Can you show me how do I have to use the function onRenderFramePre?

JonThom commented 2 years ago

It's a prop for the React component - check the docs at https://github.com/vasturiano/react-force-graph

diegozuro commented 2 years ago

I think that this prop works only for 2D graphs and I'm working on 3D. @vasturiano can you help me?

vasturiano commented 2 years ago

@diegozuro the 3D module uses WebGL and doesn't have the concept of redrawing things at every frame, that's why that method isn't applicable.

But, if you'd like to add external items to the scene, like a background or so, you can simply extend the ThreeJS scene, which you can access via the scene component method:

// assuming you have a ref associated to the Graph
const myScene = myGraphRef.current.scene();
myScene.add(/* your code */);

Though if you just want to add a static background image, it would perhaps be easier to just overlay the graph DOM element over an image, and make it's background transparent.

diegozuro commented 2 years ago

Thank you very much @vasturiano, great work!

zernabhussain commented 2 years ago

The best solution I could find for changing background.

const scene = graphRef.current.scene();
const image = require("IMAGE complete path here with extension") // for example require("assets/image.png") 
new THREE.TextureLoader().load(image, function (texture) {

            texture.mapping = THREE.EquirectangularReflectionMapping;
            scene.background = texture;
            scene.environment = texture;
        });
lichdu29 commented 2 years ago

Do you have any examples on codesandbox for changing background image? @vasturiano @zernabhussain