删除选定的矩形

时间:2016-11-19 09:37:41

标签: javascript html d3.js

无论如何我可以从多个矩形中选择矩形并使用d3.j删除所选的矩形吗?

下面是我们可以创建多个矩形并拖动的代码。 我想选择其中一个并使用按钮点击事件将其删除。这是一个完整的工作Fiddle

d3.select('#rectangle').on('click', function(){ new Rectangle(); });
d3.select('#freehand').on('click', function(){ new FreeHand(); });

var w = 600, h = 500;
var svg = d3.select('body').append('svg').attr({width: w, height: h});
function FreeHand() {

    var self = this, rect, rectData = [], isDown = false, m1, m2, isDrag = false;
    var color = d3.scale.category20();
    
    var line = d3.svg.line();
    
    var drawObj = {
      isDown: false,
      dataPoints: [],
      currentPath: null,
      color: 0
    }
svg.on('mousedown', function() {
//alert('1')
drawObj.isDown = true;
    })
    
    .on('mousemove', function() {
    //alert('2')
if (drawObj.isDown){
        drawObj.dataPoints.push(
          [d3.event.x, d3.event.y]
        );
        if (!drawObj.currentPath){
          drawObj.currentPath = svg.append("path")
            .attr("class","currentPath")
            .style("stroke-width", 1)
            .style("stroke",color(drawObj.color))
            .style("fill", "none");
        }
        drawObj.currentPath
          .datum(drawObj.dataPoints)
          .attr("d", line);
      }
    })
    .on('mouseup', function() {
          drawObj.isDown = false;
      drawObj.currentPath.attr("class","oldPath");
      drawObj.dataPoints = [];
      drawObj.currentPath = null;
      if (++drawObj.color > 19) {
        drawObj.color = 0;
      }
    });

}
function Rectangle() {
    var self = this, rect, rectData = [], isDown = false, m1, m2, isDrag = false;
    
    svg.on('mousedown', function() {
        m1 = d3.mouse(this);
        if (!isDown && !isDrag) {
            self.rectData = [ { x: m1[0], y: m1[1] }, { x: m1[0], y: m1[1] } ];
            self.rectangleElement = d3.select('svg').append('rect').attr('class', 'rectangle').call(dragR);
            self.pointElement1 = d3.select('svg').append('circle').attr('class', 'pointC').call(dragC1);
            self.pointElement2 = d3.select('svg').append('circle').attr('class', 'pointC').call(dragC2);            
            self.pointElement3 = svg.append('circle').attr('class', 'pointC').call(dragC3);
            self.pointElement4 = svg.append('circle').attr('class', 'pointC').call(dragC4);
            updateRect();
            isDrag = false;
        } else { 
            isDrag = true;
            alert('D');
        }
        isDown = !isDown;     
    })
    
    .on('mousemove', function() {
        m2 = d3.mouse(this);
        if(isDown && !isDrag) { 
            self.rectData[1] = { x: m2[0], y: m2[1] };
            updateRect();
        } 
    });  
    
    function updateRect() {  
        rect = d3.select(self.rectangleElement[0][0]);
        rect.attr({
            x: self.rectData[1].x - self.rectData[0].x > 0 ? self.rectData[0].x :  self.rectData[1].x,
            y: self.rectData[1].y - self.rectData[0].y > 0 ? self.rectData[0].y :  self.rectData[1].y,
            width: Math.abs(self.rectData[1].x - self.rectData[0].x),
            height: Math.abs(self.rectData[1].y - self.rectData[0].y)

        });   

        var point1 = d3.select(self.pointElement1[0][0]).data(self.rectData);
        point1.attr('r', 5)
              .attr('cx', self.rectData[0].x)
              .attr('cy', self.rectData[0].y);        
        var point2 = d3.select(self.pointElement2[0][0]).data(self.rectData);
        point2.attr('r', 5)
              .attr('cx', self.rectData[1].x)
              .attr('cy', self.rectData[1].y);
        var point3 = d3.select(self.pointElement3[0][0]).data(self.rectData);
        point3.attr('r', 5)
              .attr('cx', self.rectData[1].x)
              .attr('cy', self.rectData[0].y);        
        var point3 = d3.select(self.pointElement4[0][0]).data(self.rectData);
        point3.attr('r', 5)
              .attr('cx', self.rectData[0].x)
              .attr('cy', self.rectData[1].y);
    }
    
    var dragR = d3.behavior.drag().on('drag', dragRect);
    
    function dragRect() {

        var e = d3.event;
        for(var i = 0; i < self.rectData.length; i++){
            d3.select(self.rectangleElement[0][0])
                .attr('x', self.rectData[i].x += e.dx )
                .attr('y', self.rectData[i].y += e.dy );
        }
        rect.style('cursor', 'move');

        updateRect();
    }
    
    var dragC1 = d3.behavior.drag().on('drag', dragPoint1);
    var dragC2 = d3.behavior.drag().on('drag', dragPoint2);
    var dragC3 = d3.behavior.drag().on('drag', dragPoint3);
    var dragC4 = d3.behavior.drag().on('drag', dragPoint4);
    
    function dragPoint1() {
        var e = d3.event;
        d3.select(self.pointElement1[0][0])
            .attr('cx', function(d) { return d.x += e.dx })
            .attr('cy', function(d) { return d.y += e.dy });        
        updateRect();   
    }   
    
    function dragPoint2() {
        var e = d3.event;
        d3.select(self.pointElement2[0][0])
            .attr('cx', self.rectData[1].x += e.dx )
            .attr('cy', self.rectData[1].y += e.dy );
        updateRect();   
    }   
    
    function dragPoint3() {
        var e = d3.event;
        d3.select(self.pointElement3[0][0])
            .attr('cx', self.rectData[1].x += e.dx )
            .attr('cy', self.rectData[0].y += e.dy );     
        updateRect();   
    }   
    
    function dragPoint4() {
        var e = d3.event;
        d3.select(self.pointElement4[0][0])
            .attr('cx', self.rectData[0].x += e.dx )
            .attr('cy', self.rectData[1].y += e.dy );
        updateRect();   
    }   
    
}//end Rectangle
svg {
    border: solid 1px red;
    cursor: crosshair;
}
rect {
    fill: lightblue;
    stroke: blue;
    stroke-width: 2px;
}
<button id='rectangle'>Highlight</button>
<button id='freehand'>Free Hand</button>

1 个答案:

答案 0 :(得分:0)

您可以将新的新事件点击添加到矩形,将点击的矩形存储在变量

.on('click', function() {
    selected = this;
})

并添加一个新按钮Delete,删除所选矩形。

<button id='delete'>Delete</button>
d3.select('#delete').on('click', function() {
  if (typeof selected !== 'undefined' || selected !== null) {
    selected.remove();
    select = null;
  }
});

当前代码会给你一些丑陋的文物,因为它只删除了矩形,而不是删除了布局的其余部分,但至少它一般都有用。

我会将所有内容(矩形,线条,圆圈)分组到一个被删除的组元素中。

var selected;

d3.select('#rectangle').on('click', function() {
  new Rectangle();
});
d3.select('#freehand').on('click', function() {
  new FreeHand();
});
d3.select('#delete').on('click', function() {
  if (typeof selected !== 'undefined' || selected !== null) {
    selected.remove();
    select = null;
  }
});

var w = 600,
  h = 500;
var svg = d3.select('body').append('svg').attr({
  width: w,
  height: h
});


function FreeHand() {

  var self = this,
    rect, rectData = [],
    isDown = false,
    m1, m2, isDrag = false;
  var color = d3.scale.category20();

  var line = d3.svg.line();

  var drawObj = {
    isDown: false,
    dataPoints: [],
    currentPath: null,
    color: 0
  }
  svg.on('mousedown', function() {
    //alert('1')
    drawObj.isDown = true;
  })

  .on('mousemove', function() {
      //alert('2')
      if (drawObj.isDown) {
        drawObj.dataPoints.push(
          [d3.event.x, d3.event.y]
        );
        if (!drawObj.currentPath) {
          drawObj.currentPath = svg.append("path")
            .attr("class", "currentPath")
            .style("stroke-width", 1)
            .style("stroke", color(drawObj.color))
            .style("fill", "none");
        }
        drawObj.currentPath
          .datum(drawObj.dataPoints)
          .attr("d", line);
      }
    })
    .on('mouseup', function() {
      drawObj.isDown = false;
      drawObj.currentPath.attr("class", "oldPath");
      drawObj.dataPoints = [];
      drawObj.currentPath = null;
      if (++drawObj.color > 19) {
        drawObj.color = 0;
      }
    });

}

function Rectangle() {
  var self = this,
    rect, rectData = [],
    isDown = false,
    m1, m2, isDrag = false;

  svg.on('mousedown', function() {
    m1 = d3.mouse(this);
    if (!isDown && !isDrag) {
      self.rectData = [{
        x: m1[0],
        y: m1[1]
      }, {
        x: m1[0],
        y: m1[1]
      }];
      var simpleLine = d3.svg.line();
      d3.select('svg')
        .append('path')
        .attr({
          d: simpleLine([
            [self.rectData[0].x, self.rectData[0].y + Math.abs(self.rectData[1].y - self.rectData[0].y)],
            [200, self.rectData[0].y + Math.abs(self.rectData[1].y - self.rectData[0].y)]
          ]),
          stroke: '#000'
        });
      self.rectangleElement = d3.select('svg').append('rect')
        .attr('class', 'rectangle').call(dragR)
        .on('click', function() {
          window.alert('A rectangle was just selected');
          selected = this;
          
        });
      self.pointElement1 = d3.select('svg').append('circle').attr('class', 'pointC').call(dragC1);
      self.pointElement2 = d3.select('svg').append('circle').attr('class', 'pointC').call(dragC2);
      self.pointElement3 = svg.append('circle').attr('class', 'pointC').call(dragC3);
      self.pointElement4 = svg.append('circle').attr('class', 'pointC').call(dragC4);
      updateRect();
      isDrag = false;
    } else {
      isDrag = true;
    }
    isDown = !isDown;
  })

  .on('mousemove', function() {
    m2 = d3.mouse(this);
    if (isDown && !isDrag) {
      self.rectData[1] = {
        x: m2[0],
        y: m2[1]
      };
      updateRect();
    }
  });

  function updateRect() {
    rect = d3.select(self.rectangleElement[0][0]);
    rect.attr({
      x: self.rectData[1].x - self.rectData[0].x > 0 ? self.rectData[0].x : self.rectData[1].x,
      y: self.rectData[1].y - self.rectData[0].y > 0 ? self.rectData[0].y : self.rectData[1].y,
      width: Math.abs(self.rectData[1].x - self.rectData[0].x),
      height: Math.abs(self.rectData[1].y - self.rectData[0].y)

    });

    var point1 = d3.select(self.pointElement1[0][0]).data(self.rectData);
    point1.attr('r', 5)
      .attr('cx', self.rectData[0].x)
      .attr('cy', self.rectData[0].y);
    var point2 = d3.select(self.pointElement2[0][0]).data(self.rectData);
    point2.attr('r', 5)
      .attr('cx', self.rectData[1].x)
      .attr('cy', self.rectData[1].y);
    var point3 = d3.select(self.pointElement3[0][0]).data(self.rectData);
    point3.attr('r', 5)
      .attr('cx', self.rectData[1].x)
      .attr('cy', self.rectData[0].y);
    var point3 = d3.select(self.pointElement4[0][0]).data(self.rectData);
    point3.attr('r', 5)
      .attr('cx', self.rectData[0].x)
      .attr('cy', self.rectData[1].y);
  }

  var dragR = d3.behavior.drag().on('drag', dragRect);

  function dragRect() {
    var e = d3.event;
    for (var i = 0; i < self.rectData.length; i++) {
      d3.select(self.rectangleElement[0][0])
        .attr('x', self.rectData[i].x += e.dx)
        .attr('y', self.rectData[i].y += e.dy);
    }
    rect.style('cursor', 'move');

    updateRect();
  }

  var dragC1 = d3.behavior.drag().on('drag', dragPoint1);
  var dragC2 = d3.behavior.drag().on('drag', dragPoint2);
  var dragC3 = d3.behavior.drag().on('drag', dragPoint3);
  var dragC4 = d3.behavior.drag().on('drag', dragPoint4);

  function dragPoint1() {
    var e = d3.event;
    d3.select(self.pointElement1[0][0])
      .attr('cx', function(d) {
        return d.x += e.dx
      })
      .attr('cy', function(d) {
        return d.y += e.dy
      });
    updateRect();
  }

  function dragPoint2() {
    var e = d3.event;
    d3.select(self.pointElement2[0][0])
      .attr('cx', self.rectData[1].x += e.dx)
      .attr('cy', self.rectData[1].y += e.dy);
    updateRect();
  }

  function dragPoint3() {
    var e = d3.event;
    d3.select(self.pointElement3[0][0])
      .attr('cx', self.rectData[1].x += e.dx)
      .attr('cy', self.rectData[0].y += e.dy);
    updateRect();
  }

  function dragPoint4() {
    var e = d3.event;
    d3.select(self.pointElement4[0][0])
      .attr('cx', self.rectData[0].x += e.dx)
      .attr('cy', self.rectData[1].y += e.dy);
    updateRect();
  }

} //end Rectangle
svg {
  border: solid 1px red;
  cursor: crosshair;
}

rect {
  fill: lightblue;
  stroke: blue;
  stroke-width: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.13/d3.min.js"></script>
<button id='rectangle'>Highlight</button>
<button id='freehand'>Free Hand</button>
<button id='delete'>Delete</button>