0

I am trying to build simple canvas game and i am having a little bit of problem.

Say you are drawing a square or a circle and move it around, I am trying to figure out a way how to click that element that is being drawn like in html you can do.

So you could click a square, it would get highlighted and sub menu pop up that you can chose some interaction with item.

The best of my thoughts so far would be to do a collision check between a clicked point { mouse.x, mouse.y } and all elements. But this seem to be very slow method, maybe someone has a better one.

Here is some starting code that is drawing circles around some area.

var cvs, ctx, w, h, x, y, loop, mouse, pool;
    
 cvs = document.querySelector('canvas');
 ctx = cvs.getContext('2d');
    w = cvs.width = 400;
    h = cvs.height = 400;
    x = w / 2;
    y = h / 2;
    mouse = {x: x, y: y};
    pool = [];
    rnd = (min, max) => Math.floor(Math.random() * (Math.floor(max) - Math.ceil(min) + 1)) + Math.ceil(min);
    
for(var i = 0; i < 10; i++) {
 pool[i] = {
     x: rnd(5, w - 5),
        y: rnd(5, h - 5),
        r: rnd(10, 20)
    };
}

var draw_bg = function() {
 ctx.fillStyle = '#f3f5f6';
    ctx.fillRect(0, 0, w, h);
};

var draw_circle = function(_x, _y, _r, _c) {
 ctx.beginPath();
    ctx.arc(_x, _y, _r, 0, Math.PI * 2);
    ctx.strokeStyle = _c;
    ctx.stroke();
};

(loop = function() {
 draw_bg();
    
    for(var i = 0; i < pool.length; i++) {
     if(pool[i].x < 0) { pool[i].x = w; }
        if(pool[i].x > w) { pool[i].x = 0; }
        if(pool[i].y < 0) { pool[i].y = h; }
        if(pool[i].y > h) { pool[i].y = 0; }

     draw_circle(pool[i].x, pool[i].y, pool[i].r, '#5dd5dd');
    }
    
    window.requestAnimationFrame(loop);
})();

cvs.onmousemove = function(e) {
 mouse.x = e.offsetX;
    mouse.y = e.offsetY;
};
canvas {
    width:400px;
    height:400px;
    position:absolute;
    left:calc(50% - 200px);
    top:calc(50% - 200px);
    border:solid 1px #ccc;
}
<canvas></canvas>
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
  • 1
    Please share some code that you have done so it's easier to think of a solution to your specific problem. – thepio Jun 02 '17 at 07:33
  • i added link to jsfiddle with starting concept, circles are being drawn in random location. –  Jun 02 '17 at 07:40
  • Sort of off-topic, but you could make use of Fabric.js. This library renders canvas drawings based on an underlying object model. Many functionalities that you are trying to achieve are ready available out of the box as part of its core. http://fabricjs.com/ – Freeman Lambda Jun 02 '17 at 07:45

0 Answers0