Setting Up the Canvas
The HTML5 canvas element provides the foundation for Babylon.js rendering. This section covers how to properly set up your canvas element and prepare it for 3D rendering.
The canvas acts as the viewport into your 3D world, and proper setup is crucial for performance and user experience. Here's how to create a basic HTML structure with a properly configured canvas:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Babylon.js Basic Scene</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
#renderCanvas {
width: 100%;
height: 100%;
touch-action: none;
}
</style>
<script src="https://cdn.babylonjs.com/babylon.js"></script>
</head>
<body>
<canvas id="renderCanvas"></canvas>
<script src="app.js"></script>
</body>
</html>
Key canvas considerations:
- Fullscreen Canvas: Setting width and height to 100% creates an immersive experience that fills the viewport
- Touch Action: The touch-action: none CSS property prevents default touch behaviors like scrolling when interacting with the canvas
- Canvas ID: Assigning an ID makes it easy to reference the canvas in JavaScript
- Overflow Handling: Setting overflow: hidden on the body prevents scrollbars when the canvas fills the viewport
For responsive applications, you might need to handle canvas resizing when the window dimensions change:
window.addEventListener('resize', function() {
engine.resize();
});
This ensures your 3D scene maintains the correct aspect ratio and fills the available space when the browser window is resized.