2016-09-06 79 views
0

D3用於在angular2組件中生成svg。如何更新來自svg事件mousemove的組件中的屬性xy?從mousemove事件訪問時angular2 d3:將d3 svg鼠標pos更新爲組件屬性

export class AxisComponent implements OnInit { 
    x:number; 
    y:number;  

    ngOnInit() { 
     var svgWidth=400; 
     var svgHeight=400; 
     var margin = {top:25, right:25, bottom:50, left:50}; 
     var width = svgWidth - margin.left - margin.right; 
     var height = svgHeight - margin.top - margin.bottom; 

     var svg = d3.select('#container').append('svg') 
      .attr('width', svgWidth) 
      .attr('height',svgHeight) 
      .style('border', '2px solid'); 

     svg.on("mousemove", function(){ 
      var xy = d3.mouse(this); 

      this.x = xy[0]; 
      this.y = xy[0]; 
     }); 
} 

錯誤:

enter image description here

回答

3

我懷疑它應該是:

svg.on("mousemove",() => { 
    var xy = d3.mouse(svg); // or d3.mouse(d3.event.currentTarget); 
    this.x = xy[0]; 
    this.y = xy[0]; 

或者這樣說:

let self = this; 
svg.on("mousemove", function(){ 
    var xy = d3.mouse(this); 

    self.x = xy[0]; 
    self.y = xy[0]; 
}); 
+0

'd3.mouse (這)'做es不適用於'{}'? – beewest

+0

是的,我已經更新了答案 – yurzui