删除类中svg拖动的事件侦听器

时间:2017-09-18 04:49:59

标签: javascript svg

我可以拖,但是我无法移除阻力。我曾经读到那里,我曾经约束过这个" 它传递了一个新函数,我需要用局部变量做一些技巧。

但似乎无法做到。

代码:

// import "./general";

class Home {
  constructor() {
    this.svgContainer = document.getElementById("svg-container");
    console.log(this.svgContainer);
    this.pt = this.svgContainer.createSVGPoint();
    this.circleSVG = document.getElementById("circleSVG");

  }

   startDrag() {
    this.svgContainer.addEventListener("mousemove", this.mouseMoveFunc.bind(this));
    this.circleSVG.addEventListener("mouseup", this.clearEvents.bind(this));
  }

  mouseMoveFunc(e) {
    console.log(this.pt)

    this.pt.x = e.clientX;
    this.pt.y = e.clientY;

    let svgPt = this.pt.matrixTransform(this.svgContainer.getScreenCTM().inverse());
    this.circleSVG.setAttribute("cx", svgPt.x);
    this.circleSVG.setAttribute("cy", svgPt.y);
  }

  clearEvents() {
    console.log(this.svgContainer.attributes)
    this.svgContainer.removeEventListener("mousemove", this.mouseMoveFunc);
    this.circleSVG.removeEventListener("mouseup", this.clearEvents);
  }
}

var home;
window.addEventListener("load", () => {
  home = new Home();
});

这是html:

<svg id="svg-container" width="500" height="500">
     <circle cx="30" cy="30" r="30" id="circleSVG" onmousedown="home.startDrag()"></circle>
</svg>

如何使用课程来解决这个问题?

1 个答案:

答案 0 :(得分:0)

您的问题是您没有参考mousemove

上附加的功能

要克服您需要使用movemove

绑定构造函数内的this事件
  constructor() {
    //.....
    this.mouseMoveFunc = this.mouseMoveFunc.bind(this);
  }

而且使用mousedown事件代替您的明确功能,以删除mouseupmousemove个事件

&#13;
&#13;
class Home {
  constructor() {
this.svgContainer = document.getElementById("svg-container");
console.log(this.svgContainer);
this.pt = this.svgContainer.createSVGPoint();
this.circleSVG = document.getElementById("circleSVG");
this.mouseMoveFunc = this.mouseMoveFunc.bind(this);

  }

   startDrag() {
this.svgContainer.addEventListener("mousemove", this.mouseMoveFunc);
 this.circleSVG.removeEventListener('mouseup', this.startDrag);
//this.circleSVG.addEventListener("mouseup", this.clearEvents.bind(this));
  }
  
   stopDrag() {
   console.log(this.svgContainer);
   this.svgContainer.removeEventListener("mousemove", this.mouseMoveFunc);
this.circleSVG.removeEventListener('mousedown', this.startDrag);
  }

  mouseMoveFunc(e) {
console.log(this.pt)

this.pt.x = e.clientX;
this.pt.y = e.clientY;

let svgPt = this.pt.matrixTransform(this.svgContainer.getScreenCTM().inverse());
this.circleSVG.setAttribute("cx", svgPt.x);
this.circleSVG.setAttribute("cy", svgPt.y);
  }

}

var home;
window.addEventListener("load", () => {
  home = new Home();
});
&#13;
<svg id="svg-container" width="500" height="500">
     <circle cx="30" cy="30" r="30" id="circleSVG" onmouseup="home.stopDrag()" onmousedown="home.startDrag()"></circle>
</svg>
&#13;
&#13;
&#13;