Pannellum can be installed via npm or by including the script directly in your HTML.
npm:
If you’re using a Node.js environment, install Pannellum using npm:
npm install pannellum
Then, you can import it into your project:
import Pannellum from 'pannellum';
Direct inclusion (HTML):
For simpler projects, you can include the Pannellum script directly in your HTML file. Download the latest release from the Pannellum GitHub repository (https://github.com/mpetroff/pannellum/releases) and include it like so:
<script src="path/to/pannellum.js"></script>
Replace "path/to/pannellum.js"
with the actual path to the downloaded pannellum.js
file. Make sure this script is included after the <body>
tag or within a DOMContentLoaded event listener to ensure the DOM is ready.
After installation, creating a panorama viewer is straightforward. The core function is pannellum.viewer
. This function takes a single argument: a configuration object. At minimum, this object needs an id
property specifying the ID of the HTML element to contain the viewer, and a panorama
property specifying the path to your panorama image.
Here’s a basic example:
.viewer('panorama1', {
pannellum"panorama": "path/to/your/panorama.jpg"
; })
Replace "path/to/your/panorama.jpg"
with the actual path to your panorama image. This will create a basic panorama viewer within the element with the ID “panorama1”.
First, you will need a panoramic image. You can create these using a dedicated panoramic camera, or by stitching together multiple images using photo editing software such as Hugin, PTGui, or others. Ensure your image is properly formatted and high-resolution for the best viewing experience.
Next, create an HTML file (e.g., index.html
) and include the Pannellum script as described in the Installation section. Within the <body>
of your HTML, add a div
element with an ID to serve as a container for your panorama:
<!DOCTYPE html>
<html>
<head>
<title>My First Pannellum Panorama</title>
</head>
<body>
<div id="panorama1"></div>
<script src="path/to/pannellum.js"></script>
<script>
.viewer('panorama1', {
pannellum"panorama": "path/to/your/panorama.jpg"
;
})</script>
</body>
</html>
Replace "path/to/your/panorama.jpg"
with the actual path to your panorama image. Open index.html
in your web browser. You should now see your first panorama displayed! Remember to adjust the path to your pannellum.js
file accordingly.
Pannellum supports loading various panorama formats. The primary method is specifying the path to a spherical or equirectangular image in the configuration’s panorama
property. The library automatically detects the image type and handles the appropriate projection.
Supported formats generally include JPEG, PNG, and other common image formats. For optimal performance, it is recommended to use optimized images (e.g., progressive JPEGs). Very large images might impact performance; consider using image optimization techniques to reduce file size while maintaining acceptable quality.
You can also load panoramas from different sources by utilizing the panorama
option with specific parameters or using other configuration options for video or cubemap panoramas. Refer to the Configuration Options section for details on advanced loading techniques.
Hotspots allow you to add interactive elements to your panoramas. These are defined within the configuration’s hotSpots
array. Each hotspot object requires at least a pitch
, yaw
, and type
property. The type
property determines the hotspot’s behavior (e.g., info
, scene
, link
). Additional properties can customize appearance and behavior, such as text content, URL links, and associated scenes.
Example:
{"hotSpots": [
{"pitch": 10,
"yaw": 20,
"type": "info",
"text": "This is a hotspot!",
"cssClass": "custom-hotspot"
,
}
{"pitch": -5,
"yaw": -30,
"type": "scene",
"sceneId": "scene2"
}
] }
This example defines two hotspots: one displaying information and another transitioning to a different scene. Note that sceneId
requires a corresponding scene definition in the configuration.
Pannellum provides intuitive navigation controls by default. Users can drag to rotate the view, zoom in and out using the mouse wheel or touch gestures. The default navigation can be customized or disabled through configuration options. For example, you can disable mouse controls, enable keyboard controls, or specify custom controls. The library also supports automatic transitions between scenes.
A comprehensive set of configuration options allows for extensive customization of the panorama viewer. These options control aspects such as:
panorama
: The path to the panorama image or video.autoLoad
: Automatically load the panorama on initialization.pitch
& yaw
: Initial viewing angle.hfov
: Horizontal field of view.hotSpots
: Array of hotspot definitions.scenes
: Array of scene definitions for transitions.northOffset
: Rotation offset for aligning the panorama with north.keyboardControl
: Enable/disable keyboard navigation.mouseControl
: Enable/disable mouse navigation.touchControl
: Enable/disable touch navigation.showControls
: Show/hide default navigation controls.defaultScene
: Sets the initial scene to loadConsult the full configuration reference for a complete list and detailed descriptions of each option. Many options allow fine-grained customization of visual elements and behavior.
The Pannellum API provides methods to interact with the viewer programmatically after initialization. Key methods include:
pannellum.viewer(container, config)
: Creates a new panorama viewer.viewer.loadScene(sceneId)
: Loads a specified scene.viewer.setPitch(pitch)
: Sets the vertical viewing angle.viewer.setYaw(yaw)
: Sets the horizontal viewing angle.viewer.setHfov(hfov)
: Sets the horizontal field of view.viewer.getPanoramaInfo()
: Retrieve information about the current panorama.viewer.destroy()
: Removes the viewer from the DOM.The full API reference provides detailed descriptions of each method, including arguments and return values. This allows developers to dynamically control the panorama viewer and integrate it seamlessly within their applications. For more advanced usage, explore event listeners available to monitor viewer interactions and state changes.
Pannellum offers several ways to customize the user interface (UI). You can modify the appearance of the default controls, add custom controls, or even replace the entire UI with a completely custom design. This is achieved primarily through CSS styling and potentially by creating custom HTML elements to replace or augment the existing ones.
CSS Styling: Pannellum’s CSS classes are well-documented, providing targets for styling various elements, including the navigation controls, hotspots, and loading indicators. By adding custom CSS rules, you can change colors, fonts, sizes, and other visual aspects to match your application’s design.
Custom Controls: You can extend the viewer’s functionality by creating custom HTML elements and attaching event listeners to trigger actions within the Pannellum viewer, such as changing scenes or views.
Complete UI Replacement: For highly customized UIs, you might choose to create a separate UI entirely and interact with the Pannellum viewer using its API methods. This provides the maximum flexibility but requires more development effort.
Pannellum can be integrated with other JavaScript libraries to enhance its functionality. For example, you could use a library like Three.js to add 3D models to your panoramas or a mapping library to overlay geographical information. The integration typically involves adding the external library to your project and then using its API alongside the Pannellum API. Be mindful of potential conflicts between libraries; ensuring compatibility might require careful consideration of variable naming and execution order.
Beyond the built-in hotspot functionality, you can enhance interactivity by creating custom interactive elements within the panorama using techniques similar to customizing the UI. This involves adding your own HTML elements overlaid on the panorama canvas and using JavaScript event listeners to detect user interactions (clicks, mouseovers, etc.). Careful positioning is crucial to ensure your elements align correctly with the panorama’s perspective. Consider using the Pannellum API to determine the current viewer position and adjust element placement accordingly.
Pannellum provides events that enable handling user input. These events can be used to trigger actions based on user interactions, such as changes in view, hotspot clicks, or zoom events. Registering event listeners allows your application to respond dynamically to user actions within the viewer. This is particularly useful for creating custom controls and interactive experiences. For example, you can use the viewchange
event to track user navigation, or the hotspotclick
event to trigger actions related to hotspot interactions.
For optimal performance, particularly with high-resolution panoramas or complex scenes, several optimization strategies are recommended:
Image Optimization: Use appropriately sized and optimized images. Compression techniques can significantly reduce file size without significant loss in visual quality. Consider using tools and techniques to reduce the image resolution while maintaining an acceptable level of detail.
Efficient Hotspot Management: Avoid excessive numbers of hotspots, particularly complex ones, as this can impact rendering performance.
Asynchronous Loading: Load resources asynchronously to prevent blocking the main thread.
Chunking/Level of Detail (LOD): For very large panoramas, consider using techniques like tiling or level of detail to improve loading speed and reduce memory consumption. This might involve loading lower-resolution versions initially and progressively replacing them with higher-resolution versions as the user interacts with specific areas.
Minimize Unnecessary Rendering: If you’re dynamically adding elements or performing other computationally intensive operations, ensure they are efficiently managed to avoid unnecessary re-rendering.
Hotspots are defined within the hotSpots
array in the Pannellum configuration object. Each hotspot is an object with properties specifying its position, type, and behavior. The pitch
and yaw
properties determine the hotspot’s position on the panorama (in degrees, where pitch
is the vertical angle and yaw
is the horizontal angle). The type
property specifies the hotspot’s behavior (see Hotspot Types section below).
A basic hotspot definition looks like this:
{"hotSpots": [
{"pitch": 10,
"yaw": 20,
"type": "info",
"text": "This is a hotspot!"
}
] }
This creates a simple info hotspot at pitch 10 and yaw 20 degrees.
Pannellum supports several hotspot types:
info
: Displays a tooltip containing text or HTML content specified by the text
property.scene
: Transitions to a different scene defined in the scenes
array of the configuration. Requires a sceneId
property specifying the target scene’s ID.link
: Opens a URL in a new tab or window. Requires a url
property specifying the URL.custom
: Allows for entirely custom hotspot behavior through the use of event listeners. Requires JavaScript code to handle user interaction with this hotspot.Besides pitch
, yaw
, and type
, hotspots can have several other properties to customize their appearance and behavior:
text
: (For info
type) Text or HTML content to display in the tooltip.url
: (For link
type) The URL to open.sceneId
: (For scene
type) The ID of the scene to transition to.cssClass
: A CSS class to apply for custom styling.createTooltipFunc
: A function to create a custom tooltip.clickHandler
: A custom JavaScript function to handle clicks. Useful for all hotspot types.image
: Path to an image to display in place of text.width
& height
: Dimensions of the image hotspot.xOffset
& yOffset
: Position offset of the hotspot from its coordinates.Pannellum triggers events related to hotspot interactions. You can listen for these events using the on
method of the Pannellum viewer instance. The primary event is hotspotclick
, which fires when a hotspot is clicked.
Example:
var viewer = pannellum.viewer('panorama1', config);
.on('hotspotclick', function(hotspot) {
viewerconsole.log('Hotspot clicked:', hotspot);
if (hotspot.type === 'link') {
window.open(hotspot.url);
}; })
This code logs information about the clicked hotspot and opens the URL if it’s a link type hotspot. Other events might include hotspotenter
and hotspotleave
. Consult the API documentation for a comprehensive list of events.
While Pannellum doesn’t natively support animation of hotspot properties (like movement or scaling), you can achieve animation effects by manipulating hotspot properties programmatically using JavaScript’s animation capabilities (like requestAnimationFrame
or animation libraries such as GreenSock (GSAP)). This involves modifying hotspot properties over time using the Pannellum API to update the hotspot’s position, appearance, or other attributes. Note that this requires custom code and potentially frequent updates to the viewer to maintain smooth animation. The update
method of the viewer can be used to re-render the scene with the changed hotspot properties.
Pannellum primarily supports equirectangular and spherical panoramic images. While the library attempts to handle various formats, the best results are obtained using common image formats like JPEG and PNG. The library’s ability to handle other formats may vary depending on browser compatibility and image characteristics. Equirectangular images are generally preferred for their simplicity and wide browser support. Spherical images, while sometimes offering advantages in terms of projection accuracy, may require specific handling or conversion for optimal display in Pannellum.
Optimizing your panoramic images is crucial for performance and a smooth user experience. Large image files can lead to slow loading times and potential performance issues, especially on mobile devices. Here are some key optimization techniques:
Compression: Use appropriate compression techniques (e.g., JPEG for photographic images, PNG for images with sharp lines and text) to reduce file size without significant loss of visual quality. Experiment with different compression levels to find the best balance between file size and image quality.
Resolution: Use a resolution appropriate for your target audience and display devices. Very high resolutions might not be necessary for smaller screens or lower-bandwidth connections, leading to excessive download times.
Progressive JPEGs: For JPEGs, using progressive encoding allows the image to load gradually, revealing a low-resolution version quickly before progressively refining the detail. This significantly improves the perceived loading speed.
Image Resizing: If you have very high-resolution images, you may consider resizing them to a more suitable size before uploading them. This can dramatically decrease file size and improve loading times.
WebP: Consider using WebP, a modern image format offering superior compression compared to JPEG and PNG. However, ensure your target browsers support WebP before implementing it.
Creating panoramic images often involves stitching multiple photos together using specialized software. Several popular options exist, including:
The choice of software depends on your technical expertise and the complexity of your stitching needs. The result of the stitching process should be a single, seamless equirectangular or spherical image suitable for use with Pannellum.
High-resolution panoramic images offer exceptional detail but can severely impact performance. To mitigate performance issues:
Reduce Resolution: As mentioned above, reduce the resolution of your image to a size appropriate for your use case. Larger images aren’t always necessary for good visual quality, especially on smaller screens.
Tiling/Level of Detail (LOD): For extremely high-resolution panoramas, consider techniques like image tiling or level of detail (LOD) rendering. This involves dividing the image into smaller tiles and loading them on demand or using a lower-resolution version initially and progressively switching to higher-resolution versions as the user navigates closer to specific areas. This requires more advanced techniques and may involve using additional libraries or frameworks.
Image Compression: Employ aggressive but responsible compression techniques to reduce file sizes while maintaining visual quality.
Lazy Loading: Load the image only when it’s needed by the viewer, rather than loading it all at once upon page load.
By combining these techniques, you can successfully utilize high-resolution images in your Pannellum panoramas without significant performance penalties.
Several common errors can occur when working with Pannellum. Here are some frequently encountered issues and their potential solutions:
Error: Could not load panorama
: This usually indicates a problem loading the panorama image. Check the path to your image file, ensure the file exists and is accessible, and verify the image format is supported. Also check the browser’s console for more specific error messages.
Error: Invalid panorama configuration
: This error suggests there’s a problem with the configuration object you’re providing to the pannellum.viewer
function. Double-check your configuration for syntax errors, typos, and incorrect property values. Ensure all required properties (like panorama
and id
) are present and correctly formatted. Refer to the configuration options documentation for details.
Error: No element found with ID…
: This means the div
element you specified as the container for the viewer doesn’t exist in your HTML. Check your HTML for the correct ID and ensure it’s properly included in the page before initializing the Pannellum viewer.
Blank Panorama: If the panorama appears blank, but no error messages are displayed, several possibilities exist. Check that the panorama image is indeed an equirectangular or spherical image. Inspect your browser’s developer tools (usually F12) to see if any network errors occurred during image loading. Ensure the image path is correct and the server hosting the image is accessible.
Hotspot Issues: Problems with hotspots usually stem from incorrect configuration. Check the pitch
, yaw
, and type
properties are correctly defined. For custom hotspots or those relying on additional functionality, make sure the associated event listeners or functions are properly set up.
Effective debugging techniques can greatly assist in resolving Pannellum-related problems:
Browser Developer Tools: Use your browser’s developer tools (usually accessible by pressing F12) to inspect the console for error messages. The console often provides detailed information about errors and warnings encountered during the loading and execution of the Pannellum script. Inspect the network tab to ensure that your panorama images and other resources are loading successfully.
Simplify your Configuration: If you have a complex configuration, try simplifying it to isolate potential problems. Start with a basic configuration, and gradually add features back in to pinpoint where problems arise.
Check the Image: Ensure that the panorama image is correctly formatted and accessible. Test with a different image to rule out potential image-related issues.
Console Logging: Use console.log()
statements to output values and check the state of variables at different points in your code. This can help identify unexpected behavior or values.
Use a Minimal Example: If you’re facing difficulties in a complex project, create a minimal HTML page to isolate and debug your Pannellum integration separately from other code. This approach makes it easier to identify problems specifically related to Pannellum.
Pannellum is designed to be compatible with modern web browsers. While it aims for wide compatibility, optimal performance and all features might not be available in older or less common browsers. It’s generally recommended to test your application with major browsers (Chrome, Firefox, Safari, Edge) to ensure a consistent experience. Very old browsers might lack support for WebGL, which is essential for optimal Pannellum performance.
Performance issues might arise with large images or complex scenes. Address these issues using the following strategies:
Image Optimization (as described above): Use optimized images to reduce file sizes and improve loading times.
Reduce Hotspot Complexity: Excessive hotspots or complex hotspot configurations can impact performance. Minimize unnecessary hotspots.
Asynchronous Loading: Load resources asynchronously to prevent blocking the main thread during page load.
Check for Memory Leaks: Use your browser’s developer tools to detect and address memory leaks that could be causing performance degradation over time.
Optimize 3D elements: If using Three.js or similar libraries to add 3D elements, ensure optimal rendering settings and reduce the complexity of 3D models to avoid performance bottlenecks.
If performance problems persist after trying these optimizations, consider profiling your application to pinpoint specific performance bottlenecks. Your browser’s developer tools usually offer profiling tools to help identify areas for improvement.
These examples demonstrate various aspects of Pannellum’s functionality. Remember to replace placeholder image paths with your actual image files. These examples assume you have Pannellum correctly installed and included in your HTML.
This example demonstrates the simplest way to create a Pannellum viewer. It displays a single panorama image with default navigation controls.
<!DOCTYPE html>
<html>
<head>
<title>Basic Pannellum Example</title>
<script src="path/to/pannellum.js"></script> </head>
<body>
<div id="panorama"></div>
<script>
.viewer('panorama', {
pannellum"panorama": "path/to/your/panorama.jpg"
;
})</script>
</body>
</html>
Replace "path/to/your/panorama.jpg"
with the actual path to your panorama image.
This example showcases a more complex panorama with hotspots, multiple scenes, and custom styling.
<!DOCTYPE html>
<html>
<head>
<title>Advanced Pannellum Example</title>
<script src="path/to/pannellum.js"></script>
<style>
.custom-hotspot {
background-color: blue;
color: white;
}</style>
</head>
<body>
<div id="panorama"></div>
<script>
.viewer('panorama', {
pannellum"panorama": "path/to/your/panorama.jpg",
"hotSpots": [
{"pitch": 10,
"yaw": 20,
"type": "info",
"text": "This is a hotspot!",
"cssClass": "custom-hotspot"
},
]"scenes": [
{"id": "scene2",
"panorama": "path/to/your/scene2.jpg"
}
];
})</script>
</body>
</html>
This example includes a hotspot with custom styling and defines a second scene. Remember to replace "path/to/your/panorama.jpg"
and "path/to/your/scene2.jpg"
with your image paths.
This example outlines the approach for a custom UI. This is a conceptual example and requires significant custom HTML and CSS. It demonstrates the integration principle; you’ll need to adapt and expand upon it based on your UI design.
<!DOCTYPE html>
<html>
<head>
<title>Custom UI Example</title>
<script src="path/to/pannellum.js"></script>
<style>
/* Custom CSS for your UI elements */
#my-custom-controls { /* ... */ }
</style>
</head>
<body>
<div id="panorama"></div>
<div id="my-custom-controls">
<button onclick="viewer.setHfov(100)">Zoom Out</button> </div>
<script>
var viewer = pannellum.viewer('panorama', { /* ... configuration ... */ });
</script>
</body>
</html>
You would replace the placeholder comment with your custom UI HTML and include JavaScript code to interact with the Pannellum viewer’s API (e.g. viewer.setHfov()
) to control the viewer through the custom controls.
This example shows how to integrate Three.js (a 3D library). This is a high-level example and requires familiarity with Three.js. You would need to include Three.js in your project and handle the integration. This example only shows the basic setup; detailed Three.js integration would require significant additional code.
<!DOCTYPE html>
<html>
<head>
<title>Example with Three.js</title>
<script src="path/to/pannellum.js"></script>
<script src="path/to/three.js"></script>
</head>
<body>
<div id="panorama"></div>
<script>
.viewer('panorama', {
pannellum"panorama": "path/to/your/panorama.jpg",
// ... other configuration ...
// Add Three.js integration code here... (Requires significant additional code)
;
})</script>
</body>
</html>
This is a skeletal example. The actual integration with Three.js would involve creating a Three.js scene, adding 3D objects, and rendering them within the Pannellum viewer’s context. This requires advanced knowledge of both Pannellum and Three.js. Consult the documentation of both libraries for details. Remember to replace the placeholder image paths.
We welcome contributions to Pannellum! Whether you’re fixing bugs, adding features, or improving the documentation, your help is valuable. Here’s how to get started:
Fork the Repository: Fork the Pannellum repository on GitHub to your own account.
Clone your Fork: Clone your forked repository to your local machine:
git clone <your_fork_url>
Install Dependencies: Navigate to the project directory and install the necessary dependencies using npm:
cd pannellum
npm install
Set up the Development Server: Pannellum uses a development server to facilitate development and testing. Start the server using:
npm start
This will launch a development server, usually accessible at http://localhost:8080
.
Explore the Code: Familiarize yourself with the project structure and codebase. The src
directory contains the core Pannellum code.
Pannellum follows consistent coding style guidelines to ensure readability and maintainability. Adherence to these guidelines is crucial for any contributions. The project uses a combination of linters and code formatters to enforce these guidelines. It is recommended to familiarize yourself with these guidelines before starting development.
JavaScript: Follow standard JavaScript best practices. The project employs a specific linter to enforce consistency. Ensure your code passes linting checks before submitting a pull request. The specific linting configuration is usually detailed within the project’s documentation or configuration files.
CSS: Use a consistent style for CSS. This often involves using a specific CSS preprocessor and following a set of style rules related to naming conventions, indentation, and organization.
HTML: Use valid HTML5 and follow semantic HTML practices.
Commit Messages: Write clear, concise, and informative commit messages that explain the changes made in each commit. Follow a conventional commit message format for consistency.
Before submitting a pull request, make sure your code adheres to the defined style guidelines by running the appropriate linting and formatting tools.
Thorough testing is crucial to ensure the quality and stability of Pannellum. Before submitting a pull request, test your changes extensively to verify they work correctly and don’t introduce regressions.
Unit Tests: The project likely includes unit tests. Run these tests to ensure your changes haven’t broken existing functionality. The commands for running unit tests are usually included in the project’s documentation (e.g., using a test runner like Jest).
Manual Testing: Perform manual testing of your changes in different browsers and on various devices to ensure cross-browser compatibility and responsiveness. Test the different features of your changes as well.
Integration Testing: Test the integration of your changes with other parts of the Pannellum system. Test all relevant scenarios.
Address any test failures before proceeding. Well-tested changes are more likely to be accepted.
Create a Branch: Create a new branch for your changes:
git checkout -b <your_branch_name>
Make your Changes: Implement your changes, ensuring they adhere to the code style guidelines and pass all tests.
Commit your Changes: Commit your changes with descriptive commit messages:
git add .
git commit -m "Your descriptive commit message"
Push your Branch: Push your branch to your forked repository:
git push origin <your_branch_name>
Create a Pull Request: On GitHub, create a pull request from your branch to the main branch of the original Pannellum repository. Provide a clear description of your changes and address any comments or suggestions from the maintainers. The pull request should clearly outline the purpose of the changes, the problem being solved, and any relevant considerations.
Remember to follow the project’s contribution guidelines for details on specific procedures and expectations. Be patient and responsive to feedback from the project maintainers. Your contributions will help improve Pannellum for everyone!