vue实现一个拖拽生成框框并进行标注的组件,用于标记图片,地图等

577 阅读1分钟

有个功能是需要在图片上进行框选并标注,写了个小demo最终结果如图

result.png

主要就是三个事件 和控制div在data里面的插入

`

getDiv(e) {
  //  创建选框节点
  this.scrollX =
    document.documentElement.scrollLeft || document.body.scrollLeft;
  this.scrollY =
    document.documentElement.scrollTop || document.body.scrollTop;
  //  设置选框的初始位置
  this.startX = e.x + this.scrollX || e.clientX + this.scrollX;
  this.startY = e.y + this.scrollY || e.clientY + this.scrollY;
  this.List.push({
    name: "",
    top: `${this.startY}px`,
    left: `${this.startX}px`,
  });
  //  清除事件冒泡、捕获
  this.indexNow = this.List.length - 1;
  this.clearBubble(e);
  document
    .getElementById("bigDiv")
    .addEventListener("mousemove", this.mousemovefn);
  document.body.addEventListener("mouseup", this.mouseUpfn);
},
mousemovefn(e) {
  //  设置选框可见
  //  根据鼠标移动,设置选框的位置、宽高
  this.initx = e.x + this.scrollX || e.clientX + this.scrollX;
  this.inity = e.y + this.scrollY || e.clientY + this.scrollY;
  //  暂存选框的位置及宽高,用于将 select-item 选中
  this.left = Math.min(this.initx, this.startX);
  this.top = Math.min(this.inity, this.startY);
  this.width = Math.abs(this.initx - this.startX);
  this.height = Math.abs(this.inity - this.startY);
  this.List[this.indexNow].left = `${this.left - 8}px`; //8是当前大div距离 左边的距离
  this.List[this.indexNow].top = `${this.top - 60}px`; //60是当前大div距离 上边的距离
  this.List[this.indexNow].width = `${this.width}px`;
  this.List[this.indexNow].height = `${this.height}px`;
  this.$forceUpdate();
  this.clearBubble(e);
},
mouseUpfn(e) {
  document
    .getElementById("bigDiv")
    .removeEventListener("mousemove", this.mousemovefn);
  this.show = true;

  this.clearBubble(e);
},

` 三个事件配合页面结构和DATA使用

github.com/snivy2/drag… 项目地址