To set up the DrawableArea class and a corresponding RectFactory for use in CodePen, you'll need to include the JavaScript classes, some HTML to serve as the drawing container, and CSS to style the rectangles. Below is a complete example that you can directly use in CodePen.
Step 1: HTML
First, create a container element where the drawing will take place. For example, a <div> with an id of drawable-container.
<!-- HTML -->
<div id="drawable-container" class="drawable-container"></div>
Step 2: CSS
Add some basic styles to define the size and appearance of the container and the rectangles.
/* CSS */
.drawable-container {
width: 80vw;
height: 80vh;
border: 2px solid #333;
margin: 20px auto;
position: relative; /* Ensure positioning context for absolutely positioned rectangles */
background-color: #f9f9f9;
}
.rectangle {
position: absolute;
border: 2px solid #007BFF;
background-color: rgba(0, 123, 255, 0.2);
box-sizing: border-box;
}
Step 3: JavaScript
Include the DrawableArea class along with a RectFactory. The RectFactory is responsible for creating, updating, and removing rectangle elements within the container.
/* JavaScript */
/**
* RectFactory Class
* Responsible for creating and managing rectangle elements.
*/
class RectFactory {
/**
* Creates a rectangle element and appends it to the container.
* @param {Object} options - Rectangle properties.
* @param {number} options.x - The x-coordinate of the rectangle's top-left corner.
* @param {number} options.y - The y-coordinate of the rectangle's top-left corner.
* @param {number} options.width - The width of the rectangle.
* @param {number} options.height - The height of the rectangle.
* @returns {Object} - An object with `update` and `remove` methods.
*/
createRect({ x, y, width, height }) {
const rect = document.createElement('div');
rect.classList.add('rectangle');
rect.style.left = `${x}px`;
rect.style.top = `${y}px`;
rect.style.width = `${width}px`;
rect.style.height = `${height}px`;
this.container.appendChild(rect);
return {
update: ({ x, y, width, height }) => {
rect.style.left = `${x}px`;
rect.style.top = `${y}px`;
rect.style.width = `${width}px`;
rect.style.height = `${height}px`;
},
remove: () => {
if (rect.parentElement) {
rect.parentElement.removeChild(rect);
}
},
// Optional: Method to get bounding box
bbox: () => {
return {
x: parseInt(rect.style.left, 10),
y: parseInt(rect.style.top, 10),
width: parseInt(rect.style.width, 10),
height: parseInt(rect.style.height, 10),
};
},
};
}
/**
* Initializes the factory with a container.
* @param {HTMLElement} container - The container where rectangles will be added.
*/
constructor(container) {
if (!(container instanceof HTMLElement)) {
throw new TypeError('RectFactory: "container" must be an instance of HTMLElement.');
}
this.container = container;
}
}
/**
* DrawableArea Class
* Handles drawing rectangles on a specified container.
*/
class DrawableArea extends EventTarget {
// A WeakSet to keep track of initialized containers
static initializedContainers = new WeakSet();
constructor({ container, factory }) {
super(); // Initialize EventTarget
if (!container) {
throw new TypeError('DrawableArea: "container" element is required.');
}
if (!(container instanceof HTMLElement)) {
throw new TypeError('DrawableArea: "container" must be an instance of HTMLElement.');
}
if (!factory) {
throw new TypeError('DrawableArea: "factory" instance is required.');
}
this.container = container;
this.factory = factory;
// Bind event handlers to maintain context
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
// State variables
this.isDrawing = false;
this.startX = 0;
this.startY = 0;
this.currentRect = null;
// Internal flags
this.isInitialized = false;
this.isStarted = false;
}
/**
* Factory method to create and initialize a DrawableArea instance.
* @param {Object} options - Configuration options.
* @returns {DrawableArea} - The initialized DrawableArea instance.
*/
static create(options) {
const instance = new DrawableArea(options);
instance.init();
return instance;
}
/**
* Initializes the DrawableArea by preparing the container.
* Ensures that the container has the appropriate positioning context.
* Dispatches the 'init' event upon successful initialization.
*/
init() {
if (this.isInitialized) {
console.warn('DrawableArea: Already initialized.');
return this;
}
// Ensure the container has a positioning context
const position = getComputedStyle(this.container).position;
if (!['relative', 'absolute', 'fixed', 'sticky'].includes(position)) {
this.container.style.position = 'relative';
}
// Mark the container as initialized
DrawableArea.initializedContainers.add(this.container);
this.isInitialized = true;
// Dispatch the 'init' event
this.dispatchEvent(new Event('init'));
return this; // Enable method chaining
}
/**
* Starts the drawing functionality by attaching event listeners.
* Dispatches the 'start' event upon successful start.
* @returns {DrawableArea} - The DrawableArea instance for chaining.
* @throws {Error} - If the DrawableArea is not initialized.
*/
start() {
if (!this.isInitialized) {
throw new Error('DrawableArea: Must be initialized before starting.');
}
if (this.isStarted) {
console.warn('DrawableArea: Already started.');
return this;
}
// Attach mouse event listeners
this.container.addEventListener('mousedown', this.handleMouseDown);
window.addEventListener('mousemove', this.handleMouseMove);
window.addEventListener('mouseup', this.handleMouseUp);
this.isStarted = true;
// Dispatch the 'start' event
this.dispatchEvent(new Event('start'));
return this; // Enable method chaining
}
/**
* Stops the drawing functionality by detaching event listeners.
* Dispatches the 'stop' event upon successful stop.
* @returns {DrawableArea} - The DrawableArea instance for chaining.
* @throws {Error} - If the DrawableArea is not initialized.
*/
stop() {
if (!this.isInitialized) {
throw new Error('DrawableArea: Must be initialized before stopping.');
}
if (!this.isStarted) {
console.warn('DrawableArea: Not started or already stopped.');
return this;
}
// Detach mouse event listeners
this.container.removeEventListener('mousedown', this.handleMouseDown);
window.removeEventListener('mousemove', this.handleMouseMove);
window.removeEventListener('mouseup', this.handleMouseUp);
this.isStarted = false;
// If currently drawing, cancel the operation
if (this.isDrawing) {
this.isDrawing = false;
if (this.currentRect) {
this.currentRect.remove();
this.currentRect = null;
}
}
// Dispatch the 'stop' event
this.dispatchEvent(new Event('stop'));
return this; // Enable method chaining
}
/**
* Cleans up event listeners and removes the initialization flag.
* Dispatches the 'destroy' event upon successful destruction.
* @returns {DrawableArea} - The DrawableArea instance for chaining.
* @throws {Error} - If the DrawableArea is not initialized.
*/
destroy() {
if (!this.isInitialized) {
throw new Error('DrawableArea: Not initialized or already destroyed.');
}
if (this.isStarted) {
this.stop();
}
// Remove the container from the initialized set
DrawableArea.initializedContainers.delete(this.container);
this.isInitialized = false;
// Dispatch the 'destroy' event
this.dispatchEvent(new Event('destroy'));
// Additional cleanup can be performed here (e.g., removing created elements)
return this; // Enable method chaining
}
/**
* Handles the mousedown event to start drawing.
* Dispatches 'drawn:start' and 'drawn:failure' or 'drawn:success' events as appropriate.
* @param {MouseEvent} e
*/
handleMouseDown(e) {
// Only respond to left mouse button
if (e.button !== 0) return;
// Prevent drawing if clicking on an existing rectangle
if (e.target !== this.container) return;
e.preventDefault(); // Prevent text selection and other default behaviors
this.isDrawing = true;
const rect = this.container.getBoundingClientRect();
this.startX = e.clientX - rect.left;
this.startY = e.clientY - rect.top;
// Initialize the rectangle with minimal size
try {
this.currentRect = this.factory.createRect({ x: this.startX, y: this.startY, width: 0, height: 0 });
this.dispatchEvent(
new CustomEvent('drawn:start', {
detail: { rectangle: this.currentRect },
})
);
} catch (error) {
console.error('DrawableArea: Failed to create rectangle.', error);
this.isDrawing = false;
this.dispatchEvent(
new CustomEvent('drawn:failure', {
detail: { reason: 'creation_failed', error },
})
);
}
}
/**
* Handles the mousemove event to update the drawing rectangle.
* @param {MouseEvent} e
*/
handleMouseMove(e) {
if (!this.isDrawing || !this.currentRect) return;
const rect = this.container.getBoundingClientRect();
const currentX = e.clientX - rect.left;
const currentY = e.clientY - rect.top;
let x = this.startX;
let y = this.startY;
let width = currentX - this.startX;
let height = currentY - this.startY;
// Adjust for negative width
if (width < 0) {
x = currentX;
width = Math.abs(width);
}
// Adjust for negative height
if (height < 0) {
y = currentY;
height = Math.abs(height);
}
// Update the rectangle's properties using the factory's update method
try {
this.currentRect.update({ x, y, width, height });
} catch (error) {
console.error('DrawableArea: Failed to update rectangle.', error);
this.currentRect.remove();
this.currentRect = null;
this.isDrawing = false;
this.dispatchEvent(
new CustomEvent('drawn:failure', {
detail: { reason: 'update_failed', error },
})
);
}
}
/**
* Handles the mouseup event to finalize the drawing.
* Dispatches 'drawn:success' or 'drawn:failure' and a general 'drawn' event.
* @param {MouseEvent} e
*/
handleMouseUp(e) {
if (!this.isDrawing) return;
this.isDrawing = false;
// Optional: Validate the final size of the rectangle
let isSuccess = true;
let failureReason = null;
let failureError = null;
try {
// Get bounding box parameters
const { width, height } = this.currentRect.bbox();
const MIN_SIZE = 10;
if (width < MIN_SIZE || height < MIN_SIZE) {
// Remove the rectangle if it's too small
this.currentRect.remove();
isSuccess = false;
failureReason = 'rectangle_too_small';
}
} catch (error) {
console.error('DrawableArea: Failed to finalize rectangle.', error);
isSuccess = false;
failureReason = 'finalization_failed';
failureError = error;
}
// Emit events based on success or failure
if (isSuccess) {
this.dispatchEvent(
new CustomEvent('drawn:success', {
detail: { rectangle: this.currentRect },
})
);
this.dispatchEvent(
new CustomEvent('drawn', {
detail: { rectangle: this.currentRect },
})
);
} else {
this.dispatchEvent(
new CustomEvent('drawn:failure', {
detail: { reason: failureReason, error: failureError },
})
);
this.dispatchEvent(
new CustomEvent('drawn', {
detail: { rectangle: null },
})
);
}
this.currentRect = null;
}
}
// Example Usage
// Wait for the DOM to load
document.addEventListener('DOMContentLoaded', () => {
const container = document.getElementById('drawable-container');
const factory = new RectFactory(container);
const drawableArea = DrawableArea.create({ container, factory });
// Start the DrawableArea
drawableArea.start();
// Listen to events
drawableArea.addEventListener('init', () => {
console.log('DrawableArea initialized.');
});
drawableArea.addEventListener('start', () => {
console.log('DrawableArea started.');
});
drawableArea.addEventListener('stop', () => {
console.log('DrawableArea stopped.');
});
drawableArea.addEventListener('drawn:start', (e) => {
console.log('Drawing started:', e.detail.rectangle);
});
drawableArea.addEventListener('drawn:success', (e) => {
console.log('Rectangle successfully drawn:', e.detail.rectangle);
});
drawableArea.addEventListener('drawn:failure', (e) => {
console.log('Failed to draw rectangle:', e.detail.reason, e.detail.error);
});
drawableArea.addEventListener('drawn', (e) => {
if (e.detail.rectangle) {
console.log('A rectangle was drawn:', e.detail.rectangle);
} else {
console.log('Drawing failed or was canceled.');
}
});
// Optional: Add controls to stop/destroy DrawableArea
// For demonstration, we'll destroy it after 5 minutes
setTimeout(() => {
drawableArea.destroy();
console.log('DrawableArea destroyed.');
}, 300000); // 300,000 ms = 5 minutes
});
Step 4: Putting It All Together in CodePen
-
Create a New Pen: Go to CodePen and create a new pen.
-
HTML Panel: Paste the HTML code into the HTML panel.
-
CSS Panel: Paste the CSS code into the CSS panel.
-
JavaScript Panel: Paste the JavaScript code into the JS panel.
-
Run the Pen: You should see a rectangular container where you can click and drag to draw rectangles. Open the browser console to see the event logs.
Explanation
-
RectFactory: This class is responsible for creating rectangle elements (divs with the class rectangle) and providing methods to update their position and size or remove them from the DOM. It also includes a bbox method to retrieve the current bounding box of a rectangle.
-
DrawableArea: This class handles the drawing logic. It listens for mouse events to determine when the user starts drawing (mousedown), continues drawing (mousemove), and finishes drawing (mouseup). It uses the provided RectFactory to create and manage rectangle elements.
-
Event Handling: The DrawableArea dispatches various custom events (init, start, stop, drawn:start, drawn:success, drawn:failure, and drawn) to allow you to hook into different stages of the drawing process. In the example usage, event listeners log messages to the console when these events occur.
-
Example Usage: After initializing the DrawableArea with the container and factory, it starts listening for drawing events. There's also a timeout that destroys the DrawableArea after 5 minutes, demonstrating how you might clean up resources.
Customization
You can customize the appearance of the rectangles by modifying the CSS for the .rectangle class. Additionally, you can enhance the RectFactory or DrawableArea classes to include more features, such as resizing rectangles after they're drawn, adding labels, or implementing undo/redo functionality.
Feel free to modify the JavaScript to better fit your specific needs or to integrate with other components of your project.