There are several problems with the code:
- Why are you getting random x and y coordinates between 100 and the maximum edge of the canvas? Are you purposefully avoiding the top and left 100 pixels?
- Your logic will add to the array as long as the new point is more than 150 away from any
one other point. It could be right on top of one of the others.
- You are not exiting the loop after adding to the array, so you will add the same point many times.
- Depending on the size of the canvas, you will quickly run out of possible places for the new points (once you fix the logic). You could end up with an endless loop.
- Why do you take the absolute value of a number that's guaranteed to be greater than 100?
Here is a revision that works (see
http://jsfiddle.net/cD6uC/3/[
^])
I realized that you can't size a canvas as percentages, so I used the window dimensions. Also, it seemed a little weird to require the X and Y values each to be more than 150 different. Assuming you really meant for the distance between points to be more than 150, I changed the logic to use the Pythagorean theorem.
var objectArray = new Array();
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = document.getElementById('data');
var baddata = document.getElementById('baddata');
canvas.width = window.innerWidth - 50;
canvas.height = window.innerHeight - 50;
while (objectArray.length < 10) {
var addToArray = true;
var xpos = Math.floor(Math.random() * canvas.width);
var ypos = Math.floor(Math.random() * canvas.height);
if (objectArray.length > 0) {
for (var i = 0; i < objectArray.length; i++) {
var distance = Math.sqrt(Math.pow(Math.abs(xpos - objectArray[i].coX), 2) + Math.pow(Math.abs(ypos - objectArray[i].coY), 2));
if (distance < 150) {
addToArray = false;
baddata.innerHTML += '(' + xpos + ',' + ypos + ') only ' + Math.round(distance).toString() + ' from (' + objectArray[i].coX + ',' + objectArray[i].coY + ')<br>';
break;
}
}
}
if (addToArray) {
objectArray.push({ coX: xpos, coY: ypos });
ctx.fillRect(xpos,ypos,2,2);
data.innerHTML += '(' + xpos + ',' + ypos + ')<br>';
}
}