<script src="https://unpkg.com/konva@7.0.3/konva.min.js"></script>
<h1>An approach to knowing when a node is off screen - outside viewable area of stage.</h1>
<p>The large pink rect has 4 smaller satellite rects - drag large pink rect until any satellite rect is off screen and the check will indicate this by changing the pink rect red.</h1>
<p>The following are covered:</p>
  <ul>
    <li>The stage may be larger than the div that contains it. </li>
    <li>The stage may be scaled. </li>
    <li>The node (pink rect) might be on a group (green rect) which is positioned - drag the green rect then drag the pink rect to the viewport edge - tick</li>
    <li>The layer (yellow rect) may be positioned - drag the yellow rect then drag the pink rect to the viewport edge - tick</li>
    <li>The stage may be positioned - drag the yellow rect so you can get to the grey (stage) and drag it a little, then drag the pink rect to the viewport edge - tick</li>
</ul>
<p>The magic here is computing the clientrect for the node and doing and overlap test with the area of the stage container div. If no overlap then node is off screen and we do not need to draw it.</p>
<pre>
    viewPort = {x: 0, y: 0, width: containerEle.width(), height: containerEle.height()};
    if (! hasOverlap(viewPort, node.getClientRect()){
       offscreen = true;
     }
</pre>
  
<div id='settings'>
    <table>
      <tr>
        <td>
          <label for='stageScale'>Scale</label>
        </td>
        <td>
          <select id='stageScale'>
            <option >0.5</option>
            <option selected>1</option>
            <option>2</option>
            <option>3</option>

          </select>
        </td>
      </tr> 
      <tr>
        <td>
          <label>Stage pos</label>
        </td>
        <td>
          <span id='stagePos'></pan>
        </td>
      </tr>       
      <tr>
        <td>
          <label>Layer pos</label>
        </td>
        <td>
          <span id='layerPos'></pan>
        </td>
      </tr>             
      <tr>
        <td>
          <label>Group pos</label>
        </td>
        <td>
          <span id='groupPos'></pan>
        </td>
      </tr>          
   </table>
</div>
<div id="container"></div>
body {
  margin: 10;
  padding: 10;
  overflow: scroll;
  background-color: #f0f0f0;
}
#settings {
  display: inline-block;
  vertical-align: top;
  height: 400px;
  border: 1px solid black;  
  padding: 2px;  
  overflow: scroll;
}
#container {
  display: inline-block;
  position: relative;
  left: 0;
  top: 0;
  width: 800px;
  height: 400px;
  background-color: silver;  
  border: 1px solid black;
  padding: 0px;
  overflow: hidden;
}
th {
  text-align: left;
  padding-top: 5px;
  background-color: silver;
}
td {
  padding-left:15px;
}
#phrase {
  width: 120px;
  height: 200px;
}
console.clear()
let 
    scale = 1,  // we'll use scale so we confirm it works.
    stage = new Konva.Stage({ 
      container: "container",
      width: 1000,
      height: 800, 
      scaleX: scale, scaleY: scale,
      draggable: true // to check stage dragging
    }),
    
    // add a layer to check layer dragging
    layer = new Konva.Layer({draggable: true, listening: true}),  
    
    // make a group to check group dragging
    group = new Konva.Group({draggable: true, listening: true}),
    
    // make a rect object to clone to keep the clutter down.
    rect = new Konva.Rect({
      x: 40,
      y: 50,
      width: 140,
      height: 80,
      strokeWidth: 0.5,
      stroke: 'magenta',
      fill: 'magenta',
      draggable: true
    }),
    
    boxSize = 5,
    gap = 20,
    
    dot = new Konva.Rect({
      fill: 'magenta',
      width : 5,
      height: 5
    }),
    

    txt = new Konva.Text({
      fontName: 'Arial',
      fontSize: 10,
      fill: 'black'
    }),
    
    cornerText = [],
    sideDot = [],
    dotRect = [],
    viewPort = null,
    containerEle = $('#container'),
    endofdefs;

let layerRect = rect.clone({
  x:0, y:0, fill: 'gold', opacity: 0.2,  width: stage.width(), height: stage.height(), listening: true, draggable: false
}),
    groupRect = rect.clone({
      x: 0, y: 0, width: 240, height: 180, fill: 'lime', opacity: .2, listening: true, draggable: false
    });
// Add the layer to the stage.
group.add(groupRect, rect);
layer.add(layerRect, group);
stage.add(layer);

let grid = new Grid(stage, window.innerWidth, 400, 50)

layer.moveToTop();

for (var i = 0; i < 4; i++){
  
  sideDot[i] = dot.clone();
  group.add(sideDot[i]);
  
}

// demo function to collate display params from UI controls and invoke text output.
function go(){
 
  stage.scale({x: $('#stageScale').val(), y: $('#stageScale').val()});  
  viewPort = {x: stage.x(), y: stage.y(), width: containerEle.width(), height: containerEle.height()};
  let drawRect = {x: rect.x(), y: rect.y(), width: rect.width(), height: rect.height()};
  grid.draw();
  draw(drawRect)
  
  layer.moveToTop();
  layer.batchDraw();
  
}


var draw = function(drawRect){
  
  $('#stagePos').html(parseInt(stage.position().x) + ', ' + parseInt(stage.position().y))
  $('#layerPos').html(parseInt(layer.position().x) + ', ' + parseInt(layer.position().y))
  $('#groupPos').html(parseInt(group.position().x) + ', ' + parseInt(group.position().y))
  
  viewPort = {x: 0, y: 0, width: containerEle.width(), height: containerEle.height()};

  let outside = 0; 
  for (var i = 0; i < 4; i++){
    
    switch(i){
      case 0:
        setDot(sideDot[i],  drawRect.x +  (drawRect.width - sideDot[i].width())/2,  drawRect.y - (boxSize + gap));
        dotRect[i] = sideDot[i].getClientRect();
        break;
        
      case 1:
        setDot(sideDot[i],  drawRect.x +  drawRect.width + gap,  drawRect.y + (drawRect.height - sideDot[i].height())/2);             
        dotRect[i] = sideDot[i].getClientRect();
        break;

      case 2:
        setDot(sideDot[i],  drawRect.x + (drawRect.width - sideDot[i].width())/2,  drawRect.y + drawRect.height + gap);             
        dotRect[i] = sideDot[i].getClientRect();
        break;      
        
      case 3:
        setDot(sideDot[i],  drawRect.x - (sideDot[i].width() + gap),  drawRect.y + (drawRect.height - sideDot[i].height())/2);                   
        dotRect[i] = sideDot[i].getClientRect();
        break;              
    }
    rect.fill('magenta')

    // Magic check - if the viewport and node rect DO NOT overlap then the node is offscreen.
    if (! hasOverlap(i, viewPort, dotRect[i])){
       outside = 1;
     }

  }
  rect.fill('magenta')
  if (outside > 0){
    rect.fill('red')
  }

  layer.batchDraw();
  
}


function setDot(dotNode, x, y){
  dotNode.position({x: x, y: y});  
}


// refresh the canvas so we can see the text.
stage.draw();

$('#stageScale').on('change', function(){
  go();
});

// Use center-center distance check for non-rotated rects.
var hasOverlap = function(i, r1, r2){

  let w1 = r1.width, h1 = r1.height;
  let w2 = r2.width, h2 = r2.height;

  let diff = {x: Math.abs((r1.x + w1/2) - (r2.x + w2/2)), 
              y: Math.abs((r1.y + h1/2) - (r2.y + h2/2))};

  let compWidth = (r1.width + r2.width)/2,
      compHeight = (r1.height + r2.height)/2;

  let hasOverlap = ((diff.x <= compWidth) && (diff.y <= compHeight)) 

  return hasOverlap;
}


go();

stage.on('dragmove', function(){
    $('#stagePos').html(parseInt(stage.position().x) + ', ' + parseInt(stage.position().y))
  
})
layer.on('dragmove', function(){
    $('#layerPos').html(parseInt(layer.position().x) + ', ' + parseInt(layer.position().y))
  
})
group.on('dragmove', function(){
    $('#groupPos').html(parseInt(group.position().x) + ', ' + parseInt(group.position().y))
})
rect.on('dragmove', function(e){
   let drawRect = {x: e.target.x(), y: e.target.y(), width: e.target.width(), height: e.target.height()};
          
    draw(drawRect)
})



/* Make a grid on existing stage. Packed with as many optimisations as I could find.
Params:
stage : Assumes the stage already exists
x : width of grid area, e.g. 400 means grid drawn on 400 px wide area
y : height of grid area
step : the gap between grid lines.
*/
function Grid(stage, x, y, step){
  let gridLayer = new Konva.Layer({listening: false});

  stage.add(gridLayer);
  
  this.draw = function(){
    gridLayer.destroyChildren();
    
    gridLayer.scaleX(1/stage.scaleX())
    gridLayer.scaleY(1/stage.scaleY())

    let ln = new Konva.Line({x: 0, y: 0, points: [], stroke: 'black', strokeWidth: 0.5, listening: false, perfectDrawEnabled: false, transformsEnabled: 'position', shadowEnabled: false, shadowForStrokeEnabled: false }),
        txt = new Konva.Text({name: 'gridText', x:0, y: 0, width: 20, height: 10, fontSize: 10, fontFamily: 'Calibri', align: 'center', fill: 'black', listening: false, perfectDrawEnabled: false, transformsEnabled: 'position', shadowEnabled: false, shadowForStrokeEnabled: false}),
        ln1 = null,
        t1 = null

    for (let i = step; i < x; i = i + step ){
        ln1 = ln.clone({x: i, y: 0, points: [0, 0, 0, y]});
        t1 = txt.clone({x: i - 10 , y: 0 + (10 * stage.scaleX()), text: i / stage.scaleX()});
        ln1.cache();
        t1.cache();
        gridLayer.add(ln1, t1);
    }

    for (let i = step; i < y; i = i + step ){
        ln1 = ln.clone({x: 0, y: i, points: [0, 0, x, 0]});
        t1 = txt.clone({x:  0 , y: i - 5, text: i / stage.scaleY()});
        ln1.cache();
        t1.cache();
        gridLayer.add(ln1, t1);
    }  

    gridLayer.batchDraw();
    stage.draw();
  }
  this.draw();
}
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js
  2. https://cdnjs.cloudflare.com/ajax/libs/konva/7.0.3/konva.min.js