我试图用鼠标在画布上绘制矩形。这是我的第一次尝试:
private captureEvents(canvasEl: HTMLCanvasElement) {
Observable
.fromEvent(canvasEl, 'mousedown')
.subscribe((res: MouseEvent) => {
console.log('MOUSE DOWN');
const rect = canvasEl.getBoundingClientRect();
this.originPoint = new Point();
this.originPoint.x = res.clientX;
this.originPoint.y = res.clientY;
this.startPoint = new Point();
this.startPoint.x = res.clientX - rect.left;
this.startPoint.y = res.clientY - rect.top;
});
Observable
.fromEvent(canvasEl, 'mouseup')
.subscribe((res: MouseEvent) => {
console.log('MOUSE UP');
let w: number = res.clientX - this.originPoint.x ;
let h: number = res.clientY - this.originPoint.y;
this.cx.rect(this.startPoint.x, this.startPoint.y, w, h);
this.cx.stroke();
}
);
}
这有效,但它在mouseUp事件后显示矩形,我想在移动鼠标时看到绘图矩形。
答案 0 :(得分:0)
function drawRectsObservable() {
const svg = document.getElementById("drawRects");
const mousedrag = Observable.fromEvent<MouseEvent>(svg, 'mousedown')
.map(e=>({event:e, svgBounds: svg.getBoundingClientRect()}))
.map(({event, svgBounds})=> ({
rect: new Elem(svg, 'rect')
.attr('x', event.clientX - svgBounds.left)
.attr('y', event.clientY - svgBounds.top)
.attr('width', 5)
.attr('height', 5)
.attr('fill', '#95B3D7'),
svgBounds: svgBounds}))
.subscribe(({rect,svgBounds})=>{
const ox = Number(rect.attr('x')), oy = Number(rect.attr('y'));
Observable.fromEvent<MouseEvent>(svg, 'mousemove')
.takeUntil(Observable.fromEvent(svg, 'mouseup'))
.map(({clientX, clientY})=>({
rect, ox, oy,
x: clientX - svgBounds.left,
y: clientY - svgBounds.top}))
.subscribe(({rect, ox, oy, x, y})=>
rect.attr('x', Math.min(x,ox))
.attr('y', Math.min(y,oy))
.attr('width', Math.abs(ox - x))
.attr('height', Math.abs(oy - y))
);
});
}