2017-06-21 84 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做錯了。 –

相關問題