Stop render loop when canvas is no longer in browser viewport

Hello fellow Babylonians,

I have several web pages where there’s a Babylon canvas in the header / hero section of the page, with other content below it - for example: rocketclowns.com

For performance reasons, I am looking for a method to stop the Babylon render loop when the canvas is no longer in the browser viewport. What would be the best way to achieve this?

Many thanks in advance!

function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

If the element is in the viewport, the function returns true . Otherwise, it returns false.

3 Likes
var observer = new IntersectionObserver(function (entries) {
		entries.forEach(function (entry) {
			if (entry.isIntersecting) {
				// If the canvas is visible, start the engine
				engine.runRenderLoop(function () {
					if (sceneToRender) {
						sceneToRender.render()
					}
				});
			} else {
				// If the canvas is not visible, stop the engine
				engine.stopRenderLoop();
			}
		});
	}, { threshold: 0 }); // 0.2 means that engine runs when 20% of canvas is visible
	observer.observe(canvas);
3 Likes