JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"></script>
<h4>Drag shapes inside or outside the green enclosing rect</h4>

<button id="myButton">Test if shapes are enclosed in green Rect</button>
<div id="container"></div>

CSS

body {
    padding:20px;
}
#container {
    border:solid 1px #ccc;
    margin-top: 10px;
    width:350px;
    height:350px;
}

JavaScript

var stage = new Kinetic.Stage({
    container: 'container',
    width: 350,
    height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);

// create the selection rectangle

var refRect = new Kinetic.Rect({
    x: 0,
    y: 0,
    width: stage.getWidth() / 2,
    height: stage.getHeight(),
    fill: "lightgreen"
});
refRect.BB = refBoundingBox(refRect);
layer.add(refRect);

// calculte the bounding box of refRect

function refBoundingBox(refRect) {
    return ({
        left: refRect.getX(),
        top: refRect.getY(),
        right: refRect.getX() + refRect.getWidth(),
        bottom: refRect.getY() + refRect.getHeight()
    });
}


// Test enclusure for circular shapes:
// Circle,Wedge

function isCircleInBB(refBB, shape) {
    var thisX = shape.getX();
    var thisY = shape.getY();
    var thisRadius = shape.getRadius();
    return (
    thisX - thisRadius > refBB.left && thisX + thisRadius < refBB.right && thisY - thisRadius > refBB.top && thisY + thisRadius < refBB.bottom);
}

// Test enclosure for rectangular shapes:
// Rect,Image,Text,Sprite

function isRectInBB(refBB, shape) {
    var x = shape.getX();
    var y = shape.getY();
    return (
    x > refBB.left && x + shape.getWidth() < refBB.right && y > refBB.top && y + shape.getHeight() < refBB.bottom);
}

// Test enclosure for polypoint shapes:
// Line,Polygon,Blob,Spline

function isPolyInBB(refBB, shape) {
    var x = shape.getX();
    var y = shape.getY();
    return (
    x + shape.minX > refBB.left && y + shape.minY > refBB.top && x + shape.maxX < refBB.right && y + shape.maxY < refBB.bottom);
}

// Performance note: 
// precalculate minX,maxX,minY,maxY each polypoint shape

function calcMinMax(shape) {
    var minX = 1000000;
    var minY = 1000000;
    var maxX = -1000000;
    var maxY = -100000;
    var points = shape.getPoints();
    for (var i = 0; i < points.length; i++) {
        var point = points[i];
        if (point.x < minX) {
            minX = point.x;
        }
        if...