這邊有用到 fabric.js 以及 drag and drop API,沒用過的可以先去看一下基本的設定。
這邊就是要結合兩者,把圖片拖曳到 fabric.js 的 canvas 後讓圖片可以編輯。
這邊我準備兩個區塊,分別是原本的圖片,以及要使用 fabric.js 編輯的 canvas。
<div class="block source" id="source">
<img id="img1" draggable="true" src="clothes1.png" alt="">
<img id="img2" draggable="true" src="clothes2.png" alt="">
</div>
<div class="position-relative" id="canvas-container">
<canvas id="canvas" width="600" height="300"></canvas>
</div>
初始化 fabric.js 的 canvas:
const canvas = new fabric.Canvas('canvas');
偵測圖片的 drag 事件:
var images = document.querySelectorAll('#source img'); [].forEach.call(images, function (img) { img.addEventListener('dragstart', handleDragStart, false); img.addEventListener('dragend', handleDragEnd, false); }); function handleDragStart(e) { //記下來拖曳的圖片為何 e.dataTransfer.setData('text/plain',event.target.id) } function handleDragEnd(e) { }
接著在 canvas-container 偵測 drop 事件:
var canvasContainer = document.getElementById('canvas-container'); canvasContainer.addEventListener('dragenter', handleDragEnter, false); canvasContainer.addEventListener('dragover', handleDragOver, false); canvasContainer.addEventListener('dragleave', handleDragLeave, false); canvasContainer.addEventListener('drop', handleDrop, false); function handleDragEnter(e){ e.stopPropagation(); } function handleDragOver(e){ e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; return false; } function handleDragLeave(e){ }
重點是 drop 這邊,要把拖曳到裡面的圖片丟到 fabric 裡:
function handleDrop(e){ e.stopPropagation(); let id = e.dataTransfer.getData('text/plain'); var img = document.querySelector('#'+id); var newImage = new fabric.Image(img, { width: img.width, height: img.height, // Set the center of the new object based on the event coordinates relative // to the canvas container. left: e.layerX, top: e.layerY }); canvas.add(newImage); return false; }
完整程式碼: