Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="KonvaJS Template">
  <script src="https://cdn.rawgit.com/konvajs/konva/1.4.0/konva.min.js"></script>
  <meta charset="utf-8">
</head>
<body>
  <div id="container"></div>
</body>
</html>
 
body {
  padding: 0;
  margin: 0;
}
 
const stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight
});
const layer = new Konva.Layer();
stage.add(layer);
const cropRect = new Konva.Rect({
  x: 100,
  y: 100,
  width: window.innerWidth - 200,
  height: window.innerHeight - 200,
  stroke: 'black'
});
layer.add(cropRect);
const dragRect = new Konva.Rect({
  x: window.innerWidth / 2 - 50,
  y: window.innerHeight / 2 - 50,
  width: 100,
  height: 100,
  fill: 'green',
  draggable: true,
  dragBoundFunc: (pos) => {
    const leftBound = cropRect.x();
    const rightBound = cropRect.x() + cropRect.width() - dragRect.width();
    pos.x = Math.max(leftBound, Math.min(rightBound, pos.x));
    
    const topBound = cropRect.y();
    const bottomBound = cropRect.y() + cropRect.height() - dragRect.height();
    pos.y = Math.max(topBound, Math.min(bottomBound, pos.y));
    return pos;
  }
  
});
layer.add(dragRect);
layer.draw();
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers