2013-12-13 38 views
0

我使用Kinetic.js庫在JavaScript中構建繪圖板應用程序。我在徒手繪製的代碼中遇到了性能問題。基本上,我創建了一個不可見的矩形,它是舞臺的大小,然後將事件處理程序附加到它以確定繪製線的放置位置。每當鼠標移動時按住左鍵單擊按鈕,我將鼠標協調到一個數組,並使用該數組中的點來映射我的線。鼠標移動和實際渲染線之間大約有一秒的延遲。我不確定這種延遲是由我自己的代碼中的錯誤還是Kinetic庫中的限制造成的。下面是代碼:Kinetic.js渲染線在徒手繪製時緩慢使用

Whiteboard.prototype.initializeDrawings = function() { 
    // Create an invisible shape that will act as an event listener 
    var background = new Kinetic.Rect({ 
     x: 0, 
     y: 0, 
     width: this.stage.getWidth(), 
     height: this.stage.getHeight(), 
    }); 
    this.mouseDrag = false; 
    // Attach handlers 
    background.on('mousedown touchstart', function(e) { 
     this.mouseDrag = true; 
     this.currentLine = []; 
    }); 
    // Save a copy of whiteboard instance 
    var wb = this; 

    background.on('mousemove touchmove', function(e) { 
     if(this.mouseDrag === true) { 
      this.currentLine.push([e.clientX, e.clientY]); 
      wb.userDrawings.clear(); 
      wb.userDrawings.add(new Kinetic.Line({ 
       points: this.currentLine, 
       stroke: 'red', 
       strokeWidth: 4, 
       lineCap: 'round', 
       lineJoin: 'round' 
      })); 
      wb.stage.add(wb.userDrawings); 
     } 
    }); 
    background.on('mouseup touchstop', function(e) { 
     this.mouseDrag = false; 
    }); 
    this.stage.add(new Kinetic.Layer().add(background)); 
}; 

總體而言,代碼工作,但由於該應用的要求,我需要移動鼠標和渲染路徑之間的延遲顯著減少。

回答

0

你不希望創建與每一個鼠標移動新Kinetic.Line ...

爲了獲得更好的性能:

而是每創建一個新的Kinetic.Line的mousemove,在mousedown處理程序中創建一個新的行,並向mousemove中的現有行添加點。

// a var which will eventually hold a Kinetic.Line (in your class or in global scope) 

var myExistingLine; 

// in mousedown 

myExistingLine=new Kinetic.Line({ ... 

// in mousemove 

currentLine.push([mouseX,mouseY]); 

myExistingLine.setPoints(currentLine); 

myExistingLine.draw(); // or layer.drawScene(); 

要擠最高性能:

創建Kinetic.Shape,讓你訪問一個包裹的帆布背景。讓用戶在該上下文中繪製折線。在用戶創建折線後,您可以將這些點放入新的Kinetic.Line中以獲得「託管」折線的好處 - 並移除Kinetic.Shape。