Reputation: 5353
I'm trying to drop external div into fabricjs canvas. I know there is an answer Drag and Drop into Fabric.js canvas, however it didn't work for me.
Here is basic thing I'm trying to do:
let canvasContainer = document.getElementById('canvas')
canvasContainer.addEventListener('dragenter', this.onDragEnter, false);
canvasContainer.addEventListener('dragover', this.onDragOver, false);
canvasContainer.addEventListener('dragleave', this.onDragLeave, false);
canvasContainer.addEventListener('drop', this.onDrop, false);
But event handlers did not get executed.
I noticed very important thing: when I inspected DOM I found out there are two canvases: one with canvas lower-canvas
and another one with canvas upper-canvas
classes.
Only lower-cavas
has id="canvas"
property. When I deleted (manually through web inspector) upper-canvas div, event handlers did get executed.
Here how resulting HTML markup looks like:
<div class="canvas-container" style="width: 663px; height: 663px; position: relative; user-select: none;">
<canvas data-v-346adb42="" id="canvas" class="canvas lower-canvas" width="1326" height="1326" style="position: absolute; width: 663px; height: 663px; left: 0px; top: 0px; touch-action: none; user-select: none;"></canvas>
<canvas class="upper-canvas canvas" width="663" height="663" style="position: absolute; width: 663px; height: 663px; left: 0px; top: 0px; touch-action: none; user-select: none; cursor: default;"></canvas>
</div>
I'm not sure why there are two canvases. Even when I don't delete the upper-canvas, I still get green plus sign like my div is ready to be dropped.
Upvotes: 2
Views: 3096
Reputation: 15604
To bind eventlistners use canvas.on(event,handler)
.
DEMO
var canvas = new fabric.Canvas('canvas')
canvas.on('dragenter', onDragEnter, false);
canvas.on('dragover', onDragOver, false);
canvas.on('dragleave', onDragLeave, false);
canvas.on('drop', onDrop, false);
function onDragEnter() {
console.log('onDragEnter')
}
function onDragOver() {
console.log('onDragOver')
}
function onDragLeave() {
console.log('onDragLeave')
}
function onDrop() {
console.log('onDrop')
}
#canvas {
background-color: green;
}
#draggable {
width: 100px;
height: 100px;
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.2.3/fabric.js"></script>
<div id="app">
<canvas id="canvas" width=200 height=200></canvas>
<div id="draggable" draggable="true">
</div>
</div>
Here is updated fiddle.
Upvotes: 2