I am facing an issue: "How to create a rectangle on mouse down, resize it while moving, and finalize the shape on mouse up". I attempted to solve this using rxjs, but it doesn't seem like the optimal solution:
import { scan, mergeMap, takeUntil, fromEvent } from 'rxjs';
const mouseDown$ = fromEvent(document, 'mousedown');
const mouseUp$ = fromEvent(document, 'mouseup');
const mouseMove$ = fromEvent(document, 'mousemove');
function createRectangle() {
const rectangle = document.createElement('DIV');
rectangle.setAttribute('style', 'position: absolute; border: 1px solid red;');
document.body.appendChild(rectangle);
return rectangle;
}
mouseDown$
.pipe(
mergeMap(() => {
return mouseMove$.pipe(
takeUntil(mouseUp$),
scan((rectangle, e) => {
if (!rectangle) {
let x = null;
x = createRectangle();
x.style.top = `${e.clientY}px`;
x.style.left = `${e.clientX}px`;
return x;
} else {
rectangle.style.bottom = `${e.clientY}px`;
rectangle.style.right = `${e.clientX}px`;
}
return rectangle;
}, null)
);
})
)
.subscribe(() => {});
The issue lies in the side-effects being part of the "scan" method. Do you have a more efficient solution for this problem?