Basic Example (CSS Transform)
This is the most common implementation pattern for ScrollBooster. It utilizes CSS transform: translate() to pan a large canvas smoothly.
By handling the style application inside onUpdate manually (rather than relying on the automated scrollMode), you gain maximum control over the rendering pipeline. This is highly beneficial if you need to apply additional transformations (like scaling for zoom) or if you want to log coordinates for debugging.
Why CSS Transforms?
Using translate() instead of manipulating top/left or margin properties is crucial for performance. Transforms are handed off to the browser's GPU (Hardware Acceleration), meaning the browser doesn't have to recalculate the page layout (reflow) or repaint pixels on every single frame. This guarantees a silky 60 frames-per-second drag experience.
The Code
<style>
/* The Viewport limits visibility and hides overflow */
.viewport {
width: 400px;
height: 400px;
border: 5px solid #000;
overflow: hidden;
cursor: grab;
/* Prevent selection during furious dragging */
user-select: none;
/* Optional: Suggests to the browser this element will animate */
will-change: transform;
}
.viewport:active {
cursor: grabbing;
}
/* The Content provides the actual dimensions to explore */
.content {
width: 1000px;
height: 1000px;
background: repeating-linear-gradient(45deg, #e5e5e5, #e5e5e5 20px, #fff 20px, #fff 40px);
}
</style>
<div class="viewport">
<div class="content">
<h1>Drag me around!</h1>
</div>
</div>
<script type="module">
import ScrollBooster from 'scrollbooster';
const viewport = document.querySelector('.viewport');
const content = document.querySelector('.content');
const sb = new ScrollBooster({
viewport: viewport,
content: content,
bounce: true,
emulateScroll: true, // Allow mouse wheel / trackpad scrolling
// The onUpdate callback fires on requestAnimationFrame
onUpdate: (state) => {
// Manually apply the calculated coordinates to the content element.
// Notice the negative signs: moving content UP means translating it to a negative Y.
content.style.transform = `translate(
${-state.position.x}px,
${-state.position.y}px
)`;
}
});
</script>
Takeaways from this example:
- Negative Coordinates: In the
translatestring, we use${-state.position.x}. This is because when a user drags their mouse left, thestate.position.xmath increases (they are moving further right into the document), so the content itself must be physically translated to the left (negative pixels). will-changeCSS property: Addingwill-change: transformto the viewport is an optional but excellent CSS optimization that pre-allocates GPU memory for the interaction.