在框外生成随机X和Y.

时间:2016-11-25 13:50:07

标签: javascript canvas random

我想在一个方框(灰色矩形)中生成随机X和Y(红色矩形)位置

我的代码工作正常。这些位置仅在框中生成。

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

以下是fidle:https://jsfiddle.net/c2nhsbwo/

js code:

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();

如何生成位置OUTISIDE灰色矩形?

谢谢:)!

2 个答案:

答案 0 :(得分:0)

否定while语句。

切换&lt; =到&gt; =和&gt; =到&lt; =

结果:

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

答案 1 :(得分:0)

它几乎随时都在工作https://jsfiddle.net/c2nhsbwo/1/

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

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