2017-04-15 73 views
0

我有這個畫布在HTML和d & d失去了正常工作:拖放功能,當fabric.Canvas初始化

<canvas id="canvas" width="800" height="450" ondragover="onDragOver($event)" ondrop="onDrop($event)"></canvas> 

,但是當我想創建fabric.js的實例,使使用該API,D功能會丟失。

this.canvasObj = new fabric.Canvas('canvas', {}); 

如何保留功能?

回答

1

拖動&拖放功能,是因爲失去,當你創建的fabric.js帆布一個新的實例,它會自動在你的帆布面料,上面創建一個新的canvas元素(一類upper-canvas這顯然沒有拖放功能。因此,您需要將這些功能添加到新創建的畫布中。

/* for demonstration */ 
 
var ctx = document.getElementById('canvas').getContext('2d'); 
 
var text = document.getElementById('text'); 
 

 
function onDragOver(event) { 
 
    event.preventDefault(); 
 
} 
 
function onDrop(event) { 
 
    document.body.removeChild(text); 
 
    draw(); 
 
} 
 
function draw() { 
 
    ctx.clearRect(0, 0, 200, 200) 
 
    ctx.font = '14px Verdana' 
 
    ctx.fillText(text.innerText, 10, 100); 
 
    requestAnimationFrame(draw); 
 
} 
 

 
/* main part */ 
 
var canvasObj = new fabric.Canvas('canvas'); 
 
var upper_canvas = document.querySelector('.upper-canvas'); 
 
upper_canvas.ondrop = onDrop; 
 
upper_canvas.ondragover = onDragOver;
canvas { 
 
    border: 1px solid black; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.9/fabric.min.js"></script> 
 
<p draggable="true" id="text">Drag me into the canvas!</p> 
 
<canvas id="canvas" width="200" height="200" ondrop="onDrop(event)" ondragover="onDragOver(event)"></canvas>