代码之家  ›  专栏  ›  技术社区  ›  Mevia

在给定的矩形上设置3个对应点

  •  0
  • Mevia  · 技术社区  · 7 年前

    这个想法很简单,假设你有一个矩形,你想在它的边界上滚动任意点,我这样做了:

    var width = 300,
        height = 200,
        margin = 0;
    
    var rnd = function(min, max) {
        return Math.floor(Math.random() * (Math.floor(max) - Math.ceil(min) + 1)) + Math.ceil(min);
    };
    
    var point = rnd(0, (width * 2) + (height * 2));
    
    var points = [
        { x: 0, y: 0 },
        { x: 0, y: 0 },
        { x: 0, y: 0 },
        { x: 0, y: 0 }
    ]
    
    var set_point = function(point) {
        var coords = { x: 0, y: 0 };
    	
        if(point <= width) { // if on top
            coords.x = point;
            coords.y = -margin;
        } else if(point <= width + height) { // if on the right
            coords.x = width + margin;
            coords.y = point - width;
        } else if(point <= (width * 2) + height) { // if on the bottom
            coords.x = ((width * 2) + height) - point;
            coords.y = height + margin;
        } else { // if on the left
            coords.x = -margin;
            coords.y = ((width * 2) + (height * 2)) - point;
        }
    	
        return coords;
    };
    
    var test = set_point(point);
    points[0].x = test.x;
    points[0].y = test.y;
    
    for(var i = 0; i < 1 /*points.length*/; i++) {
    	var dot = document.createElement('div');
    	dot.className = 'point';
    	dot.style.left = points[i].x + 'px';
    	dot.style.top = points[i].y + 'px';
    	document.querySelector('.rect').appendChild(dot);
    }
    .rect {
        border:solid 1px #000;
        width:300px;
        height:200px;
        position:absolute;
        top:calc(50% - 100px);
        left:calc(50% - 150px);
    }
    
    .point {
        width:10px;
        height:10px;
        position:absolute;
        border-radius:100%;
        border:solid 1px red;
        background:red;
        transform:translate3d(-5px, -5px, 0);
    }
    <div class="rect"></div>

    所以现在当我有一个随机点,一个矩形,我还需要分配3个剩余的对应点,如下所示:

    enter image description here

    我试着用两种方法来做到这一点,但似乎没有一种方法能正确工作,有人知道如何根据我的方法来获得剩余的3分吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Máté Safranka    7 年前

    您需要生成一个介于0和之间的随机数 Math.min(width, height) . 我们叫这个随机数吧 d . 从这里开始,矩形内各点的坐标如下:

    • d, 0
    • width, d
    • width - d, height
    • 0, height - d

    您只需要将这个原则应用到您的实现中。