<button id="btnBlue">Blue</button>
<button id="btnGreen">Green</button>
<button id="btnYellow">Yellow</button>
<script>
document.getElementById("btnBlue").addEventListener("click", SetSceneBackground(0xADD8E6));
document.getElementById("btnBlue").addEventListener("click", SetSceneBackground(0x90EE90));
document.getElementById("btnBlue").addEventListener("click", SetSceneBackground(0xFFFF00));
// Toggle BG Color
function SetSceneBackground(colorCode) {
scene.background = new THREE.Color(colorCode);
}
</script>
Now it is obvious that since the scene is not yet initialized, this will throw an error. Scene instance is created in the init() method. How do I achieve this?
The question is where do I place this code? Since the scene gets instantiated in the init() method, it will throw an error that scene is not defined? What I am trying to do is just change the background color of the scene. However, it either does not find the scene or if I place the event listener in the init() method then it will throw some other error.
Doesn’t it mean, that you call SetSceneBackground(...) immediately in this line?
Instead, wrap this call in a function for callback: event => {SetSceneBackground(...)}.
Would be cool to provide a working live code example, that demonstrates the issue and the structure of your project.
HTML file. Please note this is just the WebGL_Loader_GLTF example from the threejs website. I am just fiddling with it for the purpose of getting hang of it.
In this current example, I have used radio button instead of button. Alert shows the right value being selected. However, the scene background color does not change yet.
And if I place the function outside <script type="module"> then it will obviously throw scene not defined error as the instance of the scene is not yet created.
i think you just need to put your SetSceneBackground function and event listeners into the same section of code that scene is defined, you’ve got it in a completely irrelevant place and out of the scope of scene, otherwise it works…