Easeljs - selecting cells under a box

making selections under a box as its moved around

by Rishi Gautam

HTML

<canvas id='mainView' width='300px' height='200px'></canvas>
<button id='clearSelection'>
Wipe my track
</button>

CSS

#mainView {
  border-style: solid;
  border-color: #354f00;
}

#clearSelection {
  display: block;
}

JavaScript

stage = new createjs.Stage('mainView');

var rectW = 80;
var rectH = 60;

createGrid(300, 200);
createSelectionBox(0, 0, rectW, rectH);
selectCells(0,0, rectW, rectH);

document.getElementById('clearSelection').addEventListener('click', function() {
	clearSelection(300, 200);
});

function createSelectionBox(x, y, w, h) {
	var shape = new createjs.Shape();
	shape.graphics
		.beginStroke("#354f00")
  	.beginFill('#354f00')
		.drawRect(x, y, w, h);
	shape.alpha = .5;
	stage.addChild(shape);
  stage.update();
  
  shape.on("pressmove", function(evt) {
    evt.target.x = evt.stageX;
    evt.target.y = evt.stageY;
    
    selectCells(evt.stageX, evt.stageY, w, h);
    stage.update();
	});
}

function selectCells(x, y, w, h) {
	var objs = stage.getObjectsUnderPoint(x, y);
  
  var cx =0, cy =0;
  
  while(cx <= w) {
  	while(cy <= h + 1) {
      var objs = stage.getObjectsUnderPoint(x + cx, y + cy);
      if(objs.length > 1) {
        objs.forEach(function(cell) {
          if(cell.id === 'cell')
            cell.alpha = 1;
        });
    	}
      cy = cy + 20;
    }
    cy = 0;
    cx+= 20;
  }
  
  stage.update();
}

function clearSelection(w,h) {
	var x =0, y=0;
	while(x <= w) {
  	while(y <= h) {
      var objs = stage.getObjectsUnderPoint(x, y);
      if(objs.length > 1) {
        objs.forEach(function(cell) {
          if(cell.id === 'cell')
            cell.alpha = .2;
        });
    	}
      y+= 20;
    }
    y = 0;
    x+= 20;
  }
  stage.update();
}

function createGrid(w, h) {
	var x = 0, y = 0;
  while(x < w) {
  	while(y < h) {
      var cell = new createjs.Shape();
      cell.graphics.beginStroke('#354f00').beginFill('#a5c663').drawRect(x, y, 20, 20);
      cell.alpha = .2;
      cell.id = 'cell';
      stage.addChild(cell);
      stage.update();
      y+=20;
    }
    y = 0;
    x+= 20;
  }
}