美文网首页
Vue + Fabric.js canvas 组件的拖拽

Vue + Fabric.js canvas 组件的拖拽

作者: 其其小宝 | 来源:发表于2021-03-23 13:35 被阅读0次

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>

思路:

  1. 首先需要定义一个临时变量 tempSrc, 用来存储每次拖拽图片的 src 地址
  2. 监听每个 img 的拖拽事件,将拖拽 target 的 src 存到 临时变量 tempSrc 中
  3. 监听 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
)

相关文章

网友评论

      本文标题:Vue + Fabric.js canvas 组件的拖拽

      本文链接:https://www.haomeiwen.com/subject/vwtfhltx.html