M
M
Michael9002019-10-18 21:39:18
JavaScript
Michael900, 2019-10-18 21:39:18

How to write an algorithm for finding the coordinates of the corners of the area of ​​intersection of two rectangles?

Confused about it. You need to find the coordinates (lower left and upper right) of the area created by the intersection of two rectangles, and display this area with a red border. What am I doing wrong?

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>new</title>
  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script src="script.js"></script>
  </body>
</html>

const WIDTH = 800;
const HEIGHT = 500;
const canvas = document.getElementById("canvas");
canvas.width = WIDTH;
canvas.height = HEIGHT;
const ctx = canvas.getContext("2d");
ctx.setTransform(1, 0, 0, -1, 0, HEIGHT);
const N = 10;
const array = [];

function rand(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

const r1 = {
  x1: rand(0, WIDTH),
  y1: rand(0, HEIGHT),
  x2: rand(0, WIDTH),
  y2: rand(0, HEIGHT)
};
const r2 = {
  x1: rand(0, WIDTH),
  y1: rand(0, HEIGHT),
  x2: rand(0, WIDTH),
  y2: rand(0, HEIGHT)
};
if (r1.x1 > r1.x2) {
  [r1.x1, r1.x2] = [r1.x2, r1.x1];
}
if (r1.y1 > r1.y2) {
  [r1.y1, r1.y2] = [r1.y2, r1.y1];
}
if (r2.x1 > r2.x2) {
  [r2.x1, r2.x2] = [r2.x2, r2.x1];
}
if (r2.y1 > r2.y2) {
  [r2.y1, r2.y2] = [r2.y2, r2.y1];
}
if (r1.y2 < r2.y1 || r1.y1 > r2.y2 || r1.x2 < r2.x1 || r1.x1 > r2.x2) {
  console.log("не пересекутся");
} else {
  console.log("пересеклись");
  let r3x1 = max(r1.y1, r2.y1),
    r3y1 = max(r1.x1, r2.x1),
    r3x2 = min(r1.y2, r2.y2),
    r3y2 = min(r1.x2, r2.x2);
  ctx.beginPath();
  ctx.strokeStyle = "red";
  ctx.strokeRect(r3x1, r3y1, r3x2 - r3x1, r3x2 - r3y1);

  ctx.beginPath();
  console.log("левый нижний: x = ", r3x1, " y = ", r3y1);
  console.log("правый верхний : x = ", r3x2, " y = ", r3y2);
}
function min(a, b) {
  if (a < b) return a;
  else return b;
}

function max(a, b) {
  if (a > b) return a;
  else return b;
}

ctx.strokeStyle = "grey";
ctx.strokeRect(r1.x1, r1.y1, r1.x2 - r1.x1, r1.y2 - r1.y1);
ctx.strokeRect(r2.x1, r2.y1, r2.x2 - r2.x1, r2.y2 - r2.y1);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question