Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <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>
              
            
!

CSS

              
                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;
}
              
            
!

JS

              
                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();
}
              
            
!
999px

Console