【问题标题】:Generate random X and Y outside a box在框外生成随机 X 和 Y
【发布时间】:2017-04-09 22:42:06
【问题描述】:

我想在一个盒子(灰色矩形)外面生成随机 X 和 Y(红色矩形)位置

我的代码工作正常,但方式很糟糕。位置仅在框中生成。

我尝试编写相反的条件,但是当我这样做时我的代码崩溃了。

这里是小提琴:https://jsfiddle.net/c2nhsbwo/

js代码:

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

var canvas = document.querySelector('canvas');
canvas.height = 900;
canvas.width = 1700;
var context = canvas.getContext('2d');

function drawBigRect() {
    context.strokeStyle = "rgb(210, 215, 211)";
    context.lineWidth = 8;
    context.strokeRect((canvas.width - 500) / 2, (canvas.height - 500) / 2, 500, 500); // debutx: 600, debuty:200, finx: 1100, finy: 700
}
// generating X and Y positions
function squareParticle() {
    var x;
    var y;
    x = rbn(25, canvas.width - 25);
    y = rbn(25, canvas.height - 25); 

   while ((600 >= x + 25)     
 ||(600 + 500 <= x) 
 || (200 >= y + 25) 
 || (200 + 500 <= y))   
{    
   x = rbn(0, canvas.width - 25);
   y = rbn(0, canvas.height - 25); 
}
    return {
        x: x,
        y: y
    };
}

var truc = {
    x: squareParticle().x,
    y: squareParticle().y
};

console.log(truc.x, truc.y);

function main() {

    context.clearRect(0,0,1700,900);

    drawBigRect();

    context.fillStyle = "red";
    context.fillRect(truc.x, truc.y, 25, 25),

    requestAnimationFrame(main);

}

main();

如何在灰色矩形之外生成位置?

谢谢:)!

【问题讨论】:

    标签: javascript canvas random


    【解决方案1】:

    否定while语句。

    将 = 和 >= 切换为

    结果:

    while (600 <= x + 25 && 600 + 500 >= x && 200 <= y + 25 && 200 + 500 >= y) {
       ...
    }
    

    【讨论】:

      【解决方案2】:

      它几乎可以在任何时候工作https://jsfiddle.net/c2nhsbwo/1/

      但有时,红色矩形仍在灰色矩形内....

      while ((600 <= x + 25) 
       &&(600 + 500 >= x) 
       && (200 <= y + 25) 
       && (200 + 500 >= y))  
      

      【讨论】:

        猜你喜欢
        • 2018-04-21
        • 1970-01-01
        • 1970-01-01
        • 2013-09-12
        • 2017-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-14
        相关资源
        最近更新 更多