2017-06-21 85 views
1

我想用鼠标在画布上绘制矩形。这是我第一次尝试:角2:用鼠标在画布上绘制矩形。

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

是的,它是以这种方式实现的。我想在拖动鼠标时看到绘图的“进度”。但我不知道如何实现这一点。 –

+0

您是否尝试过使用onmousemove事件? –

回答

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)) 
     ); 
    }); 
} 
+2

谢谢您的回答,但请不要发布的代码斑点,说明你做了什么,或/什么OP做错了。 –

相关问题