Click here to Skip to main content
15,891,828 members

How to achieve 10 random x and y co-ordinates with difference of 150

NachiketM asked:

Open original thread
I am new to html5 and JavaScript, First sorry if i ask silly question but i really need this.

I have one canvas and I want to insert 10 images at different location. So I created one array to store the co-ordinates, and I have written logic to find new location which is new to and have atleast difference of 150. I know there are many mistakes. but i cant find the locations. Help me, Thank you.

HTML
<canvas id = "canvas" height = "100%" width = "100%"></canvas>


Here is my script

JavaScript
var objectArray = new Array();
var canvas = document.getElementById("canvas");

 while (objectArray.length < 10)
        {
            xpos = Math.floor(Math.random() * (canvas.width-100)+100);
            ypos = Math.floor(Math.random() * (canvas.height-100)+100);
            if (objectArray.length > 0)
            {
                for (var i = 0; i < objectArray.length; i++)
                {
                    if
                        (
                        (xpos > (objectArray[i].coX + 150)) || (xpos + 150 < objectArray[i].coX)
                                                            &&
                        (ypos > (objectArray[i].coY + 150)) || (ypos + 150 < objectArray[i].coY)

                        )
                    {
                        objectArray.push({ coX: Math.abs(xpos), coY: Math.abs(ypos)});
                    }
                }
            }
            else
            {
                objectArray.push({ coX: Math.abs(xpos), coY: Math.abs(ypos)});
            }
        }
Tags: Javascript, HTML5, jQuery

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900