Okay, let's create a Web Component for image zooming with a rectangular zone indicator.
This component will:
- Display an original image.
- On hover, show a zoom canvas and a rectangle on the original image indicating the zoomed area.
- The zoom canvas will show a magnified view of the area under the mouse.
- The zoom level can be adjusted using the scroll wheel.
zoomable-image.js (The Web Component)
// zoomable-image.js
class ZoomableImage extends HTMLElement {
static get observedAttributes() {
return ['src', 'zoom-canvas-width', 'zoom-canvas-height'];
}
constructor() {
super();
this.attachShadow({ mode: 'open' });
this._src = '';
this._imageLoaded = false;
this._isHovering = false;
this._mousePos = { x: 0, y: 0 }; // Mouse position relative to original image's natural dimensions
// Default zoom levels (1px source -> N px zoomed)
this._zoomLevels = [1.5, 2, 3, 4, 5, 6, 8, 10]; // Multipliers
this._zoomLevelIndex = 2; // Start at 3x zoom (index 2 for 3)
this._currentZoomLevel = this._zoomLevels[this._zoomLevelIndex];
this._zoomCanvasWidth = 300; // Default zoom canvas width
this._zoomCanvasHeight = 300; // Default zoom canvas height
this._setupShadowDOM();
this._addEventListeners();
}
_setupShadowDOM() {
this.shadowRoot.innerHTML = `
<style>
:host {
display: flex; /* Use flexbox for layout of image and canvas */
flex-wrap: wrap; /* Allow wrapping if space is limited */
gap: 10px; /* Space between image and canvas */
position: relative;
user-select: none; /* Prevent accidental text selection */
border: 1px solid #ccc;
padding: 10px;
background-color: #f9f9f9;
}
.image-container {
position: relative;
line-height: 0; /* Remove extra space below image */
flex-shrink: 0; /* Don't shrink the image container */
}
#original-image {
display: block; /* Remove extra space below image */
max-width: 100%; /* Ensure image fits */
height: auto;
border: 1px solid #eee;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
#zoom-canvas {
border: 1px solid #333;
background-color: #000; /* Black background for canvas */
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
display: none; /* Hidden by default */
cursor: crosshair;
flex-shrink: 0; /* Don't shrink the canvas */
/* Fixed size for canvas, will be set by JS attributes */
}
#zoom-rect-overlay {
position: absolute;
border: 2px solid rgba(255, 0, 0, 0.7); /* Red transparent border */
background-color: rgba(255, 0, 0, 0.1); /* Light red transparent fill */
pointer-events: none; /* Allow mouse events to pass through to the image */
display: none; /* Hidden by default */
box-sizing: border-box; /* Border inside dimensions */
}
.zoom-info {
position: absolute;
bottom: 5px;
left: 5px;
background: rgba(0, 0, 0, 0.6);
color: white;
padding: 3px 8px;
border-radius: 3px;
font-family: sans-serif;
font-size: 12px;
display: none;
}
</style>
<div class="image-container">
<img id="original-image" alt="Original Image">
<div id="zoom-rect-overlay"></div>
<div class="zoom-info" id="zoom-level-info"></div>
</div>
<canvas id="zoom-canvas"></canvas>
`;
this._originalImage = this.shadowRoot.getElementById('original-image');
this._zoomCanvas = this.shadowRoot.getElementById('zoom-canvas');
this._zoomCanvasCtx = this._zoomCanvas.getContext('2d');
this._zoomRectOverlay = this.shadowRoot.getElementById('zoom-rect-overlay');
this._zoomLevelInfo = this.shadowRoot.getElementById('zoom-level-info');
// Set initial canvas size based on attributes or defaults
this._zoomCanvas.width = this._zoomCanvasWidth;
this._zoomCanvas.height = this._zoomCanvasHeight;
}
_addEventListeners() {
this._originalImage.addEventListener('load', this._handleImageLoad.bind(this));
this._originalImage.addEventListener('mouseenter', this._handleMouseEnter.bind(this));
this._originalImage.addEventListener('mouseleave', this._handleMouseLeave.bind(this));
this._originalImage.addEventListener('mousemove', this._handleMouseMove.bind(this));
this._originalImage.addEventListener('wheel', this._handleWheel.bind(this));
// Add passive: false to wheel event to ensure preventDefault works
this._originalImage.addEventListener('wheel', this._handleWheel.bind(this), { passive: false });
}
connectedCallback() {
// Load image if src is already set
if (this._src) {
this._loadImage();
}
this._updateZoomInfo();
}
disconnectedCallback() {
// Clean up listeners if necessary, though for simple cases, browser handles it.
// Good practice for complex components.
this._originalImage.removeEventListener('load', this._handleImageLoad);
this._originalImage.removeEventListener('mouseenter', this._handleMouseEnter);
this._originalImage.removeEventListener('mouseleave', this._handleMouseLeave);
this._originalImage.removeEventListener('mousemove', this._handleMouseMove);
this._originalImage.removeEventListener('wheel', this._handleWheel, { passive: false });
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue === newValue) return;
switch (name) {
case 'src':
this._src = newValue;
this._loadImage();
break;
case 'zoom-canvas-width':
this._zoomCanvasWidth = parseInt(newValue) || 300;
this._zoomCanvas.width = this._zoomCanvasWidth;
this._renderZoom(); // Re-render if canvas size changes
break;
case 'zoom-canvas-height':
this._zoomCanvasHeight = parseInt(newValue) || 300;
this._zoomCanvas.height = this._zoomCanvasHeight;
this._renderZoom(); // Re-render if canvas size changes
break;
}
}
_loadImage() {
this._imageLoaded = false;
if (this._src) {
this._originalImage.src = this._src;
}
}
_handleImageLoad() {
this._imageLoaded = true;
this._renderZoom(); // Initial render just in case, though not visible yet
}
_handleMouseEnter() {
this._isHovering = true;
this._zoomCanvas.style.display = 'block';
this._zoomRectOverlay.style.display = 'block';
this._zoomLevelInfo.style.display = 'block';
this._renderZoom(); // Render immediately on mouse enter
}
_handleMouseLeave() {
this._isHovering = false;
this._zoomCanvas.style.display = 'none';
this._zoomRectOverlay.style.display = 'none';
this._zoomLevelInfo.style.display = 'none';
}
_handleMouseMove(event) {
if (!this._imageLoaded || !this._isHovering) return;
// Calculate mouse position relative to the natural size of the image
const imgRect = this._originalImage.getBoundingClientRect();
const displayWidth = imgRect.width;
const displayHeight = imgRect.height;
const naturalWidth = this._originalImage.naturalWidth;
const naturalHeight = this._originalImage.naturalHeight;
// Scale mouse position from display pixels to natural image pixels
this._mousePos.x = (event.offsetX / displayWidth) * naturalWidth;
this._mousePos.y = (event.offsetY / displayHeight) * naturalHeight;
this._renderZoom();
}
_handleWheel(event) {
if (!this._imageLoaded || !this._isHovering) return;
event.preventDefault(); // Prevent page scroll
const direction = event.deltaY < 0 ? 1 : -1; // -1 for scroll down, 1 for scroll up
this._zoomLevelIndex = Math.max(0, Math.min(this._zoomLevels.length - 1, this._zoomLevelIndex + direction));
this._currentZoomLevel = this._zoomLevels[this._zoomLevelIndex];
this._updateZoomInfo();
this._renderZoom();
}
_updateZoomInfo() {
this._zoomLevelInfo.textContent = `Zoom: ${this._currentZoomLevel}x`;
}
_renderZoom() {
if (!this._imageLoaded || !this._isHovering) {
// Clear canvas if not hovering or image not loaded
this._zoomCanvasCtx.clearRect(0, 0, this._zoomCanvas.width, this._zoomCanvas.height);
return;
}
const naturalWidth = this._originalImage.naturalWidth;
const naturalHeight = this._originalImage.naturalHeight;
// Calculate the source rectangle (what part of the original image to draw)
// The source rectangle size depends on the zoom level and the canvas size.
// It's the area on the natural image that will fill the zoom canvas.
const sWidth = this._zoomCanvas.width / this._currentZoomLevel;
const sHeight = this._zoomCanvas.height / this._currentZoomLevel;
// Calculate top-left corner of the source rectangle, centered around mouse
let sx = this._mousePos.x - sWidth / 2;
let sy = this._mousePos.y - sHeight / 2;
// Clamp sx and sy to ensure they stay within the natural image boundaries
sx = Math.max(0, Math.min(sx, naturalWidth - sWidth));
sy = Math.max(0, Math.min(sy, naturalHeight - sHeight));
// Clear and draw on the zoom canvas
this._zoomCanvasCtx.clearRect(0, 0, this._zoomCanvas.width, this._zoomCanvas.height);
this._zoomCanvasCtx.drawImage(
this._originalImage,
sx, sy, sWidth, sHeight, // Source rectangle (x, y, width, height) from original image
0, 0, this._zoomCanvas.width, this._zoomCanvas.height // Destination rectangle (x, y, width, height) on canvas
);
// Update the zoom rectangle overlay
const imgRect = this._originalImage.getBoundingClientRect();
const displayWidth = imgRect.width;
const displayHeight = imgRect.height;
// Scale the source rectangle dimensions from natural pixels to display pixels
const scaleX = displayWidth / naturalWidth;
const scaleY = displayHeight / naturalHeight;
this._zoomRectOverlay.style.left = `${sx * scaleX}px`;
this._zoomRectOverlay.style.top = `${sy * scaleY}px`;
this._zoomRectOverlay.style.width = `${sWidth * scaleX}px`;
this._zoomRectOverlay.style.height = `${sHeight * scaleY}px`;
}
}
customElements.define('zoomable-image', ZoomableImage);
index.html (How to use the component)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zoomable Image Web Component</title>
<style>
body {
font-family: sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 20px;
background-color: #f0f0f0;
}
h1 {
color: #333;
margin-bottom: 30px;
}
/* Styles for the component itself, not within its shadow DOM */
zoomable-image {
max-width: 800px; /* Limit the overall width of the component */
border-radius: 8px;
overflow: hidden; /* To contain shadows */
}
/* You can adjust the image size displayed within the component too */
/* If you want the original image to have a specific size, you might set it here */
/* For example: */
/* zoomable-image::part(original-image) {
width: 400px;
height: auto;
} */
</style>
</head>
<body>
<h1>Image Zoomer Web Component</h1>
<zoomable-image
src="https://picsum.photos/id/237/800/600"
zoom-canvas-width="400"
zoom-canvas-height="400"
></zoomable-image>
<p style="margin-top: 30px; text-align: center; color: #555;">
Hover over the image to activate zoom. Use your scroll wheel to adjust the zoom level.
</p>
<script type="module" src="zoomable-image.js"></script>
</body>
</html>
Explanation:
-
zoomable-image.js
class ZoomableImage extends HTMLElement: Defines our custom element.
observedAttributes: Tells the component to watch for changes in src, zoom-canvas-width, and zoom-canvas-height attributes.
constructor():
attachShadow({ mode: 'open' }): Creates a Shadow DOM for encapsulation. This keeps the component's internal styles and markup separate from the rest of the page.
- Initializes internal state variables like
_src, _imageLoaded, _isHovering, _mousePos, _zoomLevels, _currentZoomLevel, and default canvas dimensions.
- Calls
_setupShadowDOM() to build the internal HTML structure and _addEventListeners() to attach event handlers.
_setupShadowDOM():
- Injects the
<style> block and the HTML structure into the Shadow DOM.
#original-image: The <img> tag that displays the original image.
#zoom-canvas: The <canvas> element where the zoomed image is drawn.
#zoom-rect-overlay: A <div> that will act as the red rectangle indicating the zoomed area on the original image. pointer-events: none; is crucial so it doesn't block mouse events on the image.
#zoom-level-info: A small overlay to show the current zoom level.
- References to these elements are stored (e.g.,
this._originalImage).
_addEventListeners():
- Listens for
load on the image (important to ensure image data is available).
- Listens for
mouseenter, mouseleave, mousemove, and wheel on the _originalImage to control the zoom behavior. wheel uses { passive: false } to allow event.preventDefault() for scroll control.
connectedCallback() / disconnectedCallback(): Standard lifecycle callbacks for when the component is added/removed from the DOM.
To use this, save the two files (zoomable-image.js and index.html) in the same directory, and open index.html in a modern web browser.