working on it ...

Filters

Explore Public Snippets

Sort by

Found 109 snippets matching: rectangles

    public by Geometry  687  0  5  0

    IsEqual: Compares two rectangles for equality, considering an acceptance threshold.

    Compares two rectangles for equality, considering an acceptance threshold.
    /// <summary>
    ///   Compares two rectangles for equality, considering an acceptance threshold.
    /// </summary>
    public static bool IsEqual(this Rectangle objA, Rectangle objB, int threshold)
    {
        return (Math.Abs(objA.X - objB.X) < threshold) &&
               (Math.Abs(objA.Y - objB.Y) < threshold) &&
               (Math.Abs(objA.Width - objB.Width) < threshold) &&
               (Math.Abs(objA.Height - objB.Height) < threshold);
    }

    public by PBMCube  125  0  4  1

    Game Box Prototype

    command combinations Description: Quickly create operational games using simple box graphics from Phaser3 shapes (v3.13.x). This test game mechanics for enjoyment. Final Artwork added to game mechanisms, prototypes and mechanics as the final pipeline product phase.
    // ============
    //Example 4.1: Prototyping Graphics begins
    // ============
    //create a character avatar using the box prototype method 
    player = box({who: this, whereX: 150, whereY: 100,length:32, width:32, color: 0x0000FF,border: 0xFFFFFF});
    this.physics.add.existing(player);
    player.body.velocity.x = 10; //see update function
    player.body.velocity.y = 50;
    console.log("Stationary Blue character avatar created as 'player' variable.");
    // ------------  
    // OR the direct method using either rectangle or graphics
    //    and set movement velocities. 
    var avatar =  this.add.rectangle(100, 100, 32, 32, 0x0000FF).setStrokeStyle(5, 0x3399CC);
    console.log("Moving Blue character avatar created as 'player' variable.");
    var graphics = this.add.graphics({ fillStyle: { color: 0xFF0000 } });
    graphics.lineStyle(10,0xFF9900,0);
    graphics.strokeRect(100, 100, 32, 32);
    	
    //non-controlled movement (usage AI bot; see Chapter 6)
    graphics.fillRectShape(avatar);
    this.physics.add.existing(avatar);
    avatar.body.velocity.x = 50;
    avatar.body.velocity.y = 10;
    //non-controlled movement (usage AI bot; see Chapter 6)
    this.physics.add.existing(graphics);
    graphics.body.velocity.x = 50;
    graphics.body.velocity.y = 50;
    console.log("Moving Red avatar created as 'avatar' variable.\n Movement velocity set.");
    // ------------
    //create an opponent - direct method 
    var monster = this.add.rectangle(180, 60, 32, 32, 0x00FF00).setStrokeStyle(5, 0xFF9900);
    console.log("Green monster avatar created as 'monster' variable.");
    //Example 4.1: ends
    // ============
    

    public by Fabax  2339  0  4  0

    From http://funprogramming.org/35-A-grid-of-rotating-objects-creates-a-wave-of-rectangles.html

    From http://funprogramming.org/35-A-grid-of-rotating-objects-creates-a-wave-of-rectangles.html: A-grid-of-rotating-objects-creates-a-wave-of-rectangles.
    float rot = 0;
    
    void setup() {
      size(400, 400);
      background(100, 200, 50);
      smooth();
      noStroke();
    }
    void draw_rotating_rectangle(float x, float y, float rect_size, float r) {
      translate(x, y);
      rotate(r);
      rect(0, 0, rect_size, rect_size);
      resetMatrix();
    }
    void draw() {
      background(100, 200, 50);
    
      float x = 0;
      while (x < 8) {
        float y = 0;
        while (y < 8) { 
          // we give a unique rotation amount to each rectangle, depending
          // on which column and row the rectangle is located (x and y)
          draw_rotating_rectangle(50 + x * 40, 50 + y * 30, 16, rot + x + y);
          y = y + 1;
        }
        x = x + 1;
      }
      rot = rot + 0.05;
    }
    
    

    external by RickyTYL  182  0  2  0

    Q: Finding the overlap : Write a function which finds the rectangle intersection of two given rectangles.Note that the rectangles are always “straight”. (Each side parallel with x-axis or y-axis)

    Q: Finding the overlap : Write a function which finds the rectangle intersection of two given rectangles.Note that the rectangles are always “straight”. (Each side parallel with x-axis or y-axis): Finding_the_overlap_function_in_Ruby
    def rec_intersection(rect1, rect2)
    
      rect3.x_min = [rect1.x_min, rect2.x_min].max
      rect3.y_min = [rect3.y_min, rect3.y_min].max
      
      rect3.x_max = [rect1.x_max, rect2.x_max].min
      rect3.y_max = [rect1.y_max, rect2.y_max].min
    
      return nil if ((x_max < x_min) || (y_max < y_min))
      return [[x_min, y_min], [x_max, y_max]]
    end
    
    

    external by datyayu  5  0  1  0

    Paiza p5, given n rectangle coords within a matrix, calculate the sum of every number inside the area composed by all of the n rectangles (removing duplicate/collisions between rectangles)

    Paiza p5, given n rectangle coords within a matrix, calculate the sum of every number inside the area composed by all of the n rectangles (removing duplicate/collisions between rectangles): Paiza_5
    var line = "4 5 3\n948 608 920 216\n3 413 306 7\n312 173 0 1000\n365 726 280 358\n26 539 197 753\n2 1 3 3\n3 3 4 4\n1 4 4 5 "
    var input = line.split(/\n/);
    
    
    // Remove first line (info) and get it's info.
    matrix_data = input.shift().split(" ");
    matrix_sizex = matrix_data[0];
    matrix_sizey = matrix_data[1];
    matrix_sizeSelection = matrix_data[2];
    
    // Remove \n's 
    input = input.filter(function (element) {
      return !element.match(/\n/);
    });
    
    // Separate the input into a array.
    var inputCleanArray = [];
    for (var i = 0; i < input.length; i++) {
      inputCleanArray[i] = input[i]
        .split(/\s/)
        .filter(function (element) {
          return !element.match(/\s/);
        })
    }
    
    // Values matrix.
    var valuesMatrix = inputCleanArray.slice(0, matrix_sizey)
    
    // Selection .
    var selections = inputCleanArray.slice(matrix_sizey, input.length) 
    
    
    // Divide matrix into top-bootom x,y pairs
    var selectionArray = []
    for (var i = 0; i < selections.length; i++) {
      selectionArray.push({
        top: {
          x: +selections[i][0],
          y: +selections[i][1]
        },
        bottom: {
          x: +selections[i][2],
          y: +selections[i][3]
        }
      });
    }
    
    // Find every coord touched by selections
    var coordsCollection = [];
    selectionArray.forEach(function(selection){
      console.log(selection)
      for(var x = selection.top.x; x <= selection.bottom.x; x++){
        for(var y = selection.top.y; y <= selection.bottom.y; y++){
          coordsCollection.push([x,y])
        }
      }
    });
    
    
    // Remove duplicates
    coordsCollection = uniq(coordsCollection)
    
    // Sum all values in the area.
    var total = 0;
    coordsCollection.forEach(function(coord){
      total += +valuesMatrix[coord[1]-1][coord[0]-1]
    })
    
    console.log(total)
    
    
    function uniq(arr) {
      var seen = {};
      var result = [];
      var len = arr.length;
      
      for (var i = 0; i < len; i++) {
        var el = arr[i];
        if (!seen[el]) {
          seen[el] = true;
          result.push(el);
        }
      }
    
      return result;
    }
    
    
    

    external by aerisdies  68  0  1  0

    Check collision between two rectangles (CreateJS)

    Check collision between two rectangles (CreateJS): script.js
    function(rect1, rect2){
    	    var dx, dy, r1={}, r2={};
    	    r1.x = rect1.x;
    	    r1.y = rect1.y;
    	    r1.bounds = rect1.getBounds();
    
    	    r2.x = rect2.x;
    	    r2.y = rect2.y;
    	    r2.bounds = rect2.getBounds();
    
    	    r1.cx = r1.x + (r1.hw = (r1.bounds.width /2));
    	    r1.cy = r1.y + (r1.hh = (r1.bounds.height/2));
    	    r2.cx = r2.x + (r2.hw = (r2.bounds.width /2));
    	    r2.cy = r2.y + (r2.hh = (r2.bounds.height/2));
    
    	    dx = Math.abs(r1.cx-r2.cx) - (r1.hw + r2.hw);
    	    dy = Math.abs(r1.cy-r2.cy) - (r1.hh + r2.hh);
    
    	    if (dx < 0 && dy < 0)
    	    {
    	        return true;
    	    } else
    	    {
    	        return false;
    	    }
    	}
    
    

    external by redgeoff  45  0  1  0

    Rotated Rectangles

    Rotated Rectangles: index.html
    <body>
    
    <script>
    
    var Point = function (x, y) {
      this.x = x;
      this.y = y;
    };
    
    var rotatePoint = function (p, rads) {
      return new Point(p.x*Math.cos(rads) - p.y*Math.sin(rads),
        p.x*Math.sin(rads) + p.y*Math.cos(rads));
    };
    
    var rotatePointAround = function (p, rads, ctr) {
      var p2 = rotatePoint(new Point(p.x - ctr.x, p.y - ctr.y), rads);
      return new Point(p2.x + ctr.x, p2.y + ctr.y);
    };
    
    var rotatePointsAround = function (points, rads, ctr) {
      var rotatedPoints = [];
    
      points.forEach(function (point) {
        rotatedPoints.push(rotatePointAround(point, rads, ctr));
      });
    
      return rotatedPoints;
    };
    
    var boundingRect = function (vertices) {
      var left = vertices[0].x,
        right = vertices[0].x,
        top = vertices[0].y,
        bottom = vertices[0].y;
    
      vertices.forEach(function (vertex) {
        if (vertex.x < left) {
          left = vertex.x;
        }
    
        if (vertex.x > right) {
          right = vertex.x;
        }
    
        if (vertex.y < top) {
          top = vertex.y;
        }
    
        if (vertex.y > bottom) {
          bottom = vertex.y;
        }
      });
    
      return { left: left, right: right, top: top, bottom: bottom };
    };
    
    var toVertices = function (x, y, width, height) {
      return [
        new Point(x, y),
        new Point(width, y),
        new Point(width, height),
        new Point(x, height)
      ];
    };
    
    var rotateAndGetBoundingRect = function (width, height, rads) {
      var vertices = toVertices(0, 0, width, height);
    
      var center = new Point(width/2, height/2);
    
      var rotatedVertices = rotatePointsAround(vertices, rads, center);
    
      return boundingRect(rotatedVertices);
    };
    
    // Allow for 1 extra pixel as the canvas's implementation of round may differ from ours by up to 1
    // pixel and we don't want to clip any pixels
    var EXTRA_PIXEL = 1;
    
    var getOffsets = function (left, top) {
    
      // Use floor so that we don't clip any pixels as we are rounding to the nearest pixel
      var x = -Math.floor(left) + EXTRA_PIXEL;
      var y = -Math.floor(top) + EXTRA_PIXEL;
    
      return { x: x, y: y };
    };
    
    var drawRotatedRect = function (canvas, width, height, rads) {
    
      // Get the bounding rect after rotation and use this to position our rectangle and size our canvas.
      var rect = rotateAndGetBoundingRect(width, height, rads);
    
      var offsets = getOffsets(rect.left, rect.top);
    
      // Use ceil so that we don't clip any pixels
      var canvasWidth = Math.ceil(rect.right) + offsets.x + EXTRA_PIXEL;
      var canvasHeight = Math.ceil(rect.bottom) + offsets.y + EXTRA_PIXEL;
      canvas.width = canvasWidth;
      canvas.height = canvasWidth;
    
      var ctx = canvas.getContext('2d');
    
      ctx.translate(offsets.x + width/2, offsets.y + height/2);
      ctx.rotate(rads);
    
      ctx.rect(-width/2, -height/2, width, height);
      ctx.stroke();
    
      return offsets;
    };
    
    var createAndDrawRotatedRect = function (x, y, width, height, rads) {
      var canvas = document.createElement('canvas');
    
      var offsets = drawRotatedRect(canvas, width, height, rads);
    
      canvas.style.position = 'absolute';
      canvas.style.left = (x - offsets.x) + 'px';
      canvas.style.top = (y - offsets.y) + 'px';
    
      document.body.appendChild(canvas);
    };
    
    var degs2Rads = function (degs) {
      return degs*Math.PI/180;
    };
    
    // -----
    
    // Starting point for 1st rectangle
    var x = 100, y = 100;
    
    var width = 100, height = 100, rads = degs2Rads(45);
    
      var rect = rotateAndGetBoundingRect(width, height, rads);
    
      var center = new Point(x + width/2, y + height/2);
    
      var rotatedVertices = rotatePointsAround(toVertices(x, y, width, height), rads, center);
    
      var offsets = getOffsets(rect.left, rect.top);
    
      createAndDrawRotatedRect(x, y, width, height, rads);
    
      var dX = Math.cos(Math.PI/2 - rads)*height;
      var dY = Math.sin(Math.PI/2 - rads)*height;
      createAndDrawRotatedRect(x + dX, y - dY, width, height, rads);
    
    </script>
    
    </body>
    
    
    

    external by cirocosta  34  0  1  0

    Select a few rectangles in an image using C++11 and OpenCV 2.4

    Select a few rectangles in an image using C++11 and OpenCV 2.4: rect_selector.cc
    #include "opencv2/opencv.hpp"
    
    #include <vector>
    #include <iostream>
    
    using cv::WINDOW_NORMAL;
    using cv::imread;
    using cv::waitKey;
    using cv::setMouseCallback;
    using cv::imshow;
    using cv::Rect;
    using cv::Point;
    using cv::Scalar;
    using cv::rectangle;
    using cv::Mat;
    
    Mat source_image;
    Mat img;
    
    // Current rectangle and start&end points
    Rect rect (0, 0, 0, 0);
    Point P1 (0, 0);
    Point P2 (0, 0);
    
    // Rectangles to be outputted
    std::vector<Rect> rects;
    
    static const char* WINDOW_NAME = "Tracking Info Generator";
    static bool clicked = false;
    
    
    void fixBoundaries () {
    	if (rect.width > img.cols - rect.x)
    		rect.width = img.cols - rect.x;
    
    	if (rect.height > img.rows - rect.y)
    		rect.height = img.rows - rect.y;
    
    	if (rect.x < 0)
    		rect.x = 0;
    
    	if (rect.y < 0)
    		rect.height = 0;
    }
    
    void draw (){
    	img = source_image.clone();
    	fixBoundaries();
    
    	for (const auto& r : rects)
    		rectangle(img, r, Scalar(0,255,0), 1, 8, 0 );
    	rectangle(img, rect, Scalar(0,255,0), 1, 8, 0 );
    
    	imshow(WINDOW_NAME, img);
    }
    
    
    void onMouse(int event, int x, int y, int f, void*){
    	switch(event){
    		case CV_EVENT_LBUTTONDOWN:
    			clicked = true;
    			P1.x = x;
    			P1.y = y;
    			P2.x = x;
    			P2.y = y;
    			break;
    
    		case  CV_EVENT_LBUTTONUP:
    			clicked = false;
    			P2.x = x;
    			P2.y = y;
    			break;
    
    		case CV_EVENT_MOUSEMOVE:
    			if (clicked) {
    				P2.x=x;
    				P2.y=y;
    			}
    			break;
    
    		default:
    			break;
    	}
    
    	if (P1.x > P2.x) {
    		rect.x = P2.x;
    		rect.width = P1.x - P2.x;
    	} else {
    		rect.x=P1.x;
    		rect.width = P2.x - P1.x;
    	}
    
    	if (P1.y > P2.y) {
    		rect.y = P2.y;
    		rect.height = P1.y - P2.y;
    	} else {
    		rect.y = P1.y;
    		rect.height = P2.y - P1.y;
    	}
    
    	draw();
    }
    
    int main()
    {
    	source_image = imread("../assets/face/faces.png", 1);
    
    	namedWindow(WINDOW_NAME, WINDOW_NORMAL);
    	setMouseCallback(WINDOW_NAME, onMouse, NULL );
    	imshow(WINDOW_NAME, source_image);
    
    	while (1) {
    		char c = waitKey();
    
    		switch (c) {
    			case 's':
    				if (rects.empty()) {
    					std::cerr << "No rect added." << std::endl
    						<< "Select an area and press 'a' to add!" << std::endl;
    					continue;
    				}
    
    				for (const auto& r : rects) {
    					std::cout << r.x + r.width/2 << " "
    						<< r.y + r.height/2 << std::endl;
    				}
    				break;
    			case 'a':
    				rects.push_back(rect);
    				rect = Rect(0, 0, 0, 0);
    				break;
    		}
    	}
    
    	return 0;
    }
    
    
    
    

    external by j  1172  12  3  0

    Drawing rectangles with Mapbox.js

    Drawing rectangles with Mapbox.js: index.html
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset=utf-8 />
        <title>Leaflet bounds</title>
        <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
        <script src='https://api.mapbox.com/mapbox.js/v2.1.9/mapbox.js'></script>
        <link href='https://api.mapbox.com/mapbox.js/v2.1.9/mapbox.css' rel='stylesheet' />
        <style>
          body { margin:0; padding:0; }
          #map { position:absolute; top:0; bottom:0; width:100%; }
        </style>
      </head>
      <body>
        <div id='map'></div>
        <script>
          L.mapbox.accessToken = 'pk.eyJ1IjoiamFjcXVlcyIsImEiOiJuRm9TWGYwIn0.ndryRT8IT0U94pHV6o0yng';
    
          var sw = L.latLng(43.46998, -67.28759),
              ne = L.latLng(45.64633, -64.17956),
              bounds = L.latLngBounds(sw, ne);
    
          // Instantiate the map
          var map = L.mapbox.map('position', 'jacques.m3h4e0b4', {
            scrollWheelZoom: false
          }).fitBounds(bounds);
    
          // Draw a polygon representing the scene boundaries
          L.rectangle(bounds, {
            fillColor: 'red'
          }).addTo(map);
        </script>
      </body>
    </html>
    
    

    external by velentr  22  0  1  0

    rectangles in tikz

    rectangles in tikz: Tikz
    \usetikzlibrary{shapes.geometric}
    \tikzstyle{rec} = [rectangle, minimum width=2cm, minimum height=2cm, text centered, draw=black, fill=white]
    
    
    
    • Public Snippets
    • Channels Snippets