2016-11-28 68 views
0

在我的fabricjs應用程序中,我創建了動態畫布(變量也是動態的)。在這裏,當鼠標在畫布上移動時,我需要檢測特定的畫布。 示例代碼,Fabricjs - 如何檢測鼠標移動的畫布?

var i = 0, canvasArray = []; 
$(this).find('canvas').each(function() { 
    i++; 
    var DynamicCanvas = 'canvas_'+i; 
    canvasArray[DynamicCanvas] = new fabric.Canvas('canvas_'+i,{ 
     width : '200', 
     height : '200' 
    }); 
}); 

之後,我有4個不同的畫布。最後添加的畫布已被激活。但我需要在任何畫布上添加對象。 因此,我必須使用鼠標移動事件來激活畫布。我怎麼能實現它。?請幫助我。

回答

1

Mullainathan,

這裏使用jQuery一些快速的解決方案:

var canvasStr = ''; 
var canvasArray = []; 
var fabricCanvasArray = []; 
var htmlStr = ''; 
var canvas = null; 

//generate canavases 
for (var i = 0; i < 4; i++){ 
      canvasArray.push('c' + i); 
      htmlStr += '<canvas id="c' + i + '" width="200" height="200"></canvas>' 
} 
//append canvasses to the body 
$('body').append(htmlStr); 

//to the fabricjs parent div elements assign id's and generate string for jQuery with div id's 
for (var i in canvasArray){ 
     fabricCanvasArray[i] = new fabric.Canvas(canvasArray[i], { 
    isDrawingMode: true 
     }); 

     $('#' + canvasArray[i]).parent().attr('id', ('div' + canvasArray[i])); 
    canvasStr += '#div' + canvasArray[i]; 
    if (i < canvasArray.length - 1){ 
      canvasStr += ','; 
    } 
} 

//jQuery event for mouse over each div element of the fabric canvas 
$(canvasStr).mouseover(function(){ 
    for (var i in fabricCanvasArray){ 
     if (fabricCanvasArray[i].lowerCanvasEl.id == $(this).children(':first').attr('id')){ 

     canvas = fabricCanvasArray[i]; 
     canvas.freeDrawingBrush.width = 10; 
     var r = 255 - i*50; 
     var g = i * 50; 
     var b = 200 - i * 40; 
     canvas.freeDrawingBrush.color = 'rgb(' + r + ',' + g + ',' + b + ')'; 
     canvas.on('mouse:up', function() { 
      //do your stuff 
     // canvas.renderAll(); 
     }); 
     break; 
    } 
    } 
}); 

此外,您還可以運行fiddle