Estoy tratando de colocar un rectángulo de tamaño aleatorio en el centro de un lienzo de 1200x1200, con un tamaño mínimo de 200x200 y un tamaño máximo de 900x900. Sin embargo, también me gustaría establecer un área máxima (de la mitad del espacio máximo de 900x900) en el rectángulo para evitar que sea un cuadrado gigante. Básicamente, quiero crear grandes rectángulos aleatorios o cuadrados de un área similar, pero nunca cuadrados enormes. Tengo la parte del rectángulo aleatorio funcionando, pero no estoy seguro de cómo limitar el área general.
var maxSize = new Size(700, 700); // max size of 900x900 when combined with +200 below var randomSize = Size.random(); // random number between 0 and 1 var size = (maxSize * randomSize) + 200; // effectively creates a 200x200 minimum size, max 900x400 var box = new Rectangle(new Point(0,0), size); // creates rectangle at 0,0 with size box.center = (600, 600); // centers rectangle at 600,600 var path = new Path.Rectangle(box); // draws rectangle on screen path.fillColor = '#cccccc';Tienes dos restricciones, tu tamaño máximo y área...
Supongo que necesitamos cumplir con ambos, necesitaremos obtener el mínimo entre esos
El area de un rectangulo es igual al producto de su largo por su ancho
Con un área dada podemos obtener un lado máximo como un cuadrado del área = Math.sqrt(max_area)
Integrando eso a tu código:
const max_area = 788544 var max_side = Math.sqrt(max_area) - 200 var maxSize = new Size(Math.min(700, max_side), Math.min(700, max_side)); ...Según la respuesta anterior, terminé generando ancho y alto aleatorios, luego verifiqué la altura contra un max_height extrapolado del área y el ancho. Probablemente haya una manera de simplificarlo, pero parece funcionar bien. ¡Gracias!
// Get random integer between two values, inclusive function getRandomLength(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1) + min); } var max_area = 260000; var width = getRandomLength(200,900); var random_height = getRandomLength(200,900); var max_height = max_area / width; var height = Math.min(random_height, max_height); var size = new Size(width, height); var box = new Rectangle(new Point(0,0), size); box.center = (600, 600); // centers rectangle at 600,600 var boxPath = new Path.Rectangle(box); boxPath.fillColor = '#cccccc';