Vue 代码示例
<div id="images">
<img draggable="true" @dragstart="handleDragEnter" src="http://i.imgur.com/8rmMZI3.jpg" width="250" height="250"></img>
<img draggable="true" @dragstart="handleDragEnter" src="http://i.imgur.com/q9aLMza.png" width="252" height="295"></img>
<img draggable="true" @dragstart="handleDragEnter" src="http://i.imgur.com/wMU4SFn.jpg" width="238" height="319"></img>
</div>
<div id="canvas-container">
<canvas id="canvas" width="800" height="600"></canvas>
</div>
思路:
- 首先需要定义一个临时变量 tempSrc, 用来存储每次拖拽图片的 src 地址
- 监听每个 img 的拖拽事件,将拖拽 target 的 src 存到 临时变量 tempSrc 中
- 监听 canvas 的拖拽事件,将 tempSrc 添加到 canvas 中
伪代码:
private handleDragEnter(e) {
// console.log("handleDragEnter:", e);
this.$emit("update:currDropImgUrl", e.target.currentSrc);
}
// canvas 监听画布拖拽事件
this.canvas.on("drop", (options: any) => {
console.log("drop:", options);
console.log("currDropImgUrl:", this.currDropImgUrl);
this.addImage({
file_url: this.currDropImgUrl,
angle: 0,
opacity: 1,
left: options.e.offsetX, // 图片相对画布的左侧距离
top: options.e.offsetY, // 图片相对画布的顶部距离
});
});
参考链接:
[Drag and Drop into Fabric.js canvas](fabricjs - Drag and Drop into Fabric.js canvas - Stack Overflow
)
网友评论