Get Click Event of Each Rectangle Inside Canvas

get click event of each rectangle inside canvas?

You're basically going to have to track where your rectangles are on the canvas, then set up an event listener on the canvas itself. From there you can take the coordinates of the click event and go through all your rectangles to test for 'collisions'.

Here's an example of doing just that: http://jsfiddle.net/9WWqG/2/

html:

<canvas id="myCanvas" width="300" height="150"></canvas>

javascript:

// get canvas element.
var elem = document.getElementById('myCanvas');

function collides(rects, x, y) {
var isCollision = false;
for (var i = 0, len = rects.length; i < len; i++) {
var left = rects[i].x, right = rects[i].x+rects[i].w;
var top = rects[i].y, bottom = rects[i].y+rects[i].h;
if (right >= x
&& left <= x
&& bottom >= y
&& top <= y) {
isCollision = rects[i];
}
}
return isCollision;
}

// check if context exist
if (elem && elem.getContext) {
// list of rectangles to render
var rects = [{x: 0, y: 0, w: 50, h: 50},
{x: 75, y: 0, w: 50, h: 50}];
// get context
var context = elem.getContext('2d');
if (context) {

for (var i = 0, len = rects.length; i < len; i++) {
context.fillRect(rects[i].x, rects[i].y, rects[i].w, rects[i].h);
}

}

// listener, using W3C style for example
elem.addEventListener('click', function(e) {
console.log('click: ' + e.offsetX + '/' + e.offsetY);
var rect = collides(rects, e.offsetX, e.offsetY);
if (rect) {
console.log('collision: ' + rect.x + '/' + rect.y);
} else {
console.log('no collision');
}
}, false);
}

How to recognize a click on a drawn rectangle on canvas

IMO it would be better to keep track of the rectangles inside an array and just loop through them to see if it's inside.

As stated Here:

When you draw to a canvas element, you are simply drawing a bitmap in
immediate mode.

The elements (shapes, lines, images) that are drawn have no
representation besides the pixels they use and their colour.[...]

Here comes the BUT: I found this Alternative

HTML5 canvas: find out if click co-ordinates are inside a given rectangle

This is a general topology problem frequently encountered when using maps.

The algorithm for deciding whether a point is within ANY polygon (rectangles, circles, irregular shapes) is as follows:

  • From the point being checked construct any line in any direction until the edge of the screen area in which your polygons are located

  • if the line intersects any polygon boundary at an odd number of places then it is within that polygon

  • if the line intersects any polygon boundary an even number of places it is outside that polygon.

           ------------
    | |
    | o--|------------------- 1 intersection: inside
    | |
    -------------
    ------------
    | |
    o------|-----------|------------------- 2 intersections: outside
    | |
    -------------

Notes:

  • The direction of the line is irrelevant

  • Will not work if a polygon is cut at the side of the screen without closure

  • If the polygon cuts over itself then the algorithm can fail if the line
    happens to pass through the cutpoint (eg in the figure 8 considered as a
    single polygon where the line passes exactly through where upper and lower
    parts connect of the figure connect)

How to add an event listener to a rectangle drawn on a canvas?

What you want to do isn't possible - at least not in such way.
The problem is that the canvas doesn't actually know about the shape of things
you draw onto. It merely knows about individual pixel color.

What you can do however is keep the bounding box - screen position and dimensions -
of your button(s) as a Path2D rectangle and use the context.isPointInPath(path2d,x,y) function to check
if someone clicked inside the area occupied by a button on your canvas.

Here's an example (just click on 'Run code snippet'):

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var image = new Image();
var buttons = [];

function draw(e) {
let x, y, width, height, path;

// first button
x = 20;
y = 20;
width = 100;
height = 20;
context.drawImage(e.target, x, y, width, height);
path = new Path2D();
path.rect(x, y, width, height);
buttons.push(path);

// second button
x = 150;
y = 20;
width = 100;
height = 20;
context.drawImage(e.target, x, y, width, height);
path = new Path2D();
path.rect(x, y, width, height);
buttons.push(path);
}

function canvasClicked(e) {
let button;
for (var a = 0; a < buttons.length; a++) {
button = buttons[a];
if (context.isPointInPath(button, e.offsetX, e.offsetY)) {
console.log("button " + (a + 1) + " clicked");
}
}
}

image.onload = draw;
image.src = "https://picsum.photos/id/866/200/300";
canvas.addEventListener("click", canvasClicked);
<canvas id="canvas" style="background-color:grey;"></canvas>

How to execute a function on mouse click on rectangle HTML5 Canvas

Here's a no-library way which involves:

  1. Listening for mousedown events:

    var canvas=document.getElementById("canvas");

    canvas.onmousedown=handleMousedown;
  2. Testing if the clicked mouse position is inside the rectangle:

    var rect={x:100,y:100,w:75,h:40};

    // mx & my are the mouse coordinates
    if(mx>=rect.x && mx<=rect.x+rect.w && my>=rect.y && my<=rect.y+rect.h){
    alert("clicked in rect");
    }

Here's example code and a Demo:

var canvas=document.getElementById("canvas");

var ctx=canvas.getContext("2d");

var BB,BBoffsetX,BBoffsetY;

setBB();

var rect={x:100,y:100,w:75,h:40};

ctx.fillRect(rect.x,rect.y,rect.w,rect.h);

canvas.onmousedown=handleMousedown;

function handleMousedown(e){

e.preventDefault();

e.stopPropagation();

var mx=e.clientX-BBoffsetX;

var my=e.clientY-BBoffsetY;

if(mx>=rect.x && mx<=rect.x+rect.w && my>=rect.y && my<=rect.y+rect.h){

alert("clicked in rect");

}

}

function setBB(){

BB=canvas.getBoundingClientRect();

BBoffsetX=BB.left;

BBoffsetY=BB.top;

}
body{ background-color: ivory; }

canvas{border:1px solid red;}
<h4>Click in the rect for an alert</h4>

<canvas id="canvas" width=300 height=300></canvas>

Detect which rectangle has been clicked in Canvas WPF

You can get your rectangle by name like this if all rectangles are bounded to OnMouseDownEvent to Rectangle_OnMouseDown function :

private void Rectangle_OnMouseDown(object sender, MouseButtonEventArgs e)
{
var mouseWasDownOn = e.Source as FrameworkElement;
if (mouseWasDownOn != null)
{
string elementName = mouseWasDownOn.Name;
var myRectangle = (Rectangle)this.FindName(elementName);
}
}

How do I click on an event that uses an object in the javascript canvas?

You can't, really. When you're drawing on a canvas you're essentially drawing one big bitmap image. The shapes you draw get added to it and that's it. They're not actually objects.

You have two options:

  1. Catch the click event from the canvas element, get the mouse coordinates and use that to infer which object was clicked.
  2. Use a library like EaselJS. It's sort of an API around the canvas that makes working with it much easier. It will allow you to attach click handlers to the objects on the canvas.


Related Topics



Leave a reply



Submit