Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8031481
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T01:06:47+00:00 2026-06-05T01:06:47+00:00

Im trying to get a hit test/overlap test to work in the below code

  • 0

Im trying to get a hit test/overlap test to work in the below code which creates 200 circles in a random position on a canvas. I am trying to store the positions of the circles in an array and then checking that array each time another circle is created in the for loop, if the randomly created x and y is too close to a already created circle it should keep getting a new random x and y until it isnt too close to an already created circle.

I just cant get it too work in the while loop.

Any help please…

Thanks

    <script type="text/javascript">

    document.addEventListener("DOMContentLoaded", canvasDraw);


    function canvasDraw () {
    var c = document.getElementById("canvas");
    var w = window.innerWidth;
    var h = window.innerHeight;
    c.width = w;
    c.height = h;

    var ctx = c.getContext("2d");
    ctx.clearRect(0,0,c.width, c.height);
    var abc = 0;

    var colours = new Array ("rgb(0,100,0)", "rgb(51,102,255)");
    var positions = new Array();


    function hitTest(x, y) {
    for(var p in positions) {
            pp = p.split(",");
        pp[0] = parseInt(pp[0]);
        pp[1] = parseInt(pp[1]);

        if(((x > (pp[0] - 24)) && (x < (pp[0] + 24))) && ((y > (pp[1] - 24)) && (y < (pp[1] + 24)))) {

            return true;
        }
    }
    return false;
}


            //Loop 200 times for 200 circles
    for (i=0; i<200; i++) {

        var x = Math.floor(Math.random()*c.width);
        var y = Math.floor(Math.random()*c.height);

        while(hitTest(x, y) == true){
            var x = Math.floor(Math.random()*c.width);
            var y = Math.floor(Math.random()*c.height);
        }

        var pos = x.toString() + "," + y.toString();
        positions.push(pos);

        var radius = 10;
        var r = radius.toString();

        var b = colours[Math.floor(Math.random()*colours.length)];

        circle(ctx,x,y, radius, b);

    }   
   }



    function circle (ctx, x, y, radius, b) {
  ctx.fillStyle = b;
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI*2, true);
  ctx.closePath();
  ctx.fill();
   }
  </script>

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T01:06:49+00:00Added an answer on June 5, 2026 at 1:06 am

    Some things before beginning:

    1. Don’t create arrays with new Array(), unless you specify the initial length. Use [];
    2. Don’t iterate through arrays using for...in: use a standard for with a counter. This is more a good practice;
    3. Converting numbers into strings and converting back to numbers is useless and expensive. Use a small array to store both values;
    4. Don’t use “magic numbers”, i.e. number with a precise value but hard to recognize immediately. Use named “constants” or put a comment near each of them telling what they mean, for future maintenance.

    Ok, let’s see the code.

    if(((x > (pp[0] - 24)) && (x < (pp[0] + 24))) && ((y > (pp[1] - 24)) && (y < (pp[1] + 24))))
    

    Honestly, what is this? I’d call it a cranky and obscure snippet. Recall what you’ve learnt at school:

    var dx = pp[0] - x, dy = pp[1] - y;
    if (dx * dx + dy * dy < 400) return true;
    

    Isn’t it much clearer?

    Let’s see the whole function:

    function canvasDraw () {
        var c = document.getElementById("canvas");
        var w = window.innerWidth;
        var h = window.innerHeight;
        c.width = w;
        c.height = h;
    
        var ctx = c.getContext("2d");
        ctx.clearRect(0,0,c.width, c.height);
        // Lolwut?
        // var abc = 0;
    
        var colours = ["rgb(0,100,0)", "rgb(51,102,255)"];
        var positions = [];
    
    
        function hitTest(x, y) {
            for (var j = 0; j < positions.length; j++) {
                var pp = positions[j];
                var dx = pp[0] - x, dy = pp[1] - y;
                if (dx * dx + dy * dy < 400) return true;
            }
            return false;
        }
    
    
        // You declare the radius once and for all
        var radius = 10;
        // Declare the local scoped variables. You forgot i
        var x, y, i;
        for (i=0; i<200; i++) {
    
            // How about a do...while instead of a while?
            do {
                var x = Math.floor(Math.random()*c.width);
                var y = Math.floor(Math.random()*c.height);
            // Testing with === is faster, always do it if you know the type
            // I'll let it here, but if the type is boolean, you can avoid testing
            // at all, as in while (hitTest(x, y));
            } while (hitTest(x, y) === true);
    
            positions.push([x, y]);
    
            // This instruction is useless
            // var r = radius.toString();
    
            var b = colours[Math.floor(Math.random()*colours.length)];
    
            circle(ctx,x,y, radius, b);
    
        }   
    }
    

    BEWARE, though, that depending on your canvas size, there could be no more room for another circle, so it could end in an infinite loop. Try to put 200 circles with a radius of 10 inside a 40×40 box…
    There should be another test to do, and that could be complicated.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

My I am trying to get the hang of android development, but I've hit
I'm trying to get the hang of using variables in C#, but have hit
When trying to hit an environment with improperly configured SSL certificates, I get the
I am trying get Struts 2 and Tiles to work and I am using
I am trying to get the four corners of my object. To test out
I am trying to test the following code snippet. static void StartAndKill() { Process
I'm trying get extended key state WNDPROC lpfnEditWndProc; //edit - hwnd of edit control
I'm trying get text of the selected drop down item My drop down list
I'm trying get the path of a folder in my project called EmailAttachments. I
I am trying get all html links within a string and replace them using

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.