angular2 d3: update d3 svg mouse pos to component property

烈酒焚心 提交于 2020-01-07 07:42:03

问题


D3 is used to generate a svg in an angular2 component. How to update properties x and y in component from svg event mousemove?

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];
        });
}

Error when accessing from mousemove event:


回答1:


I suspect it should be:

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

Or this way:

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

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


来源:https://stackoverflow.com/questions/39350774/angular2-d3-update-d3-svg-mouse-pos-to-component-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!