Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find coordinates of an HTML5 Canvas (click) event, with borders

There are a lot of answers, here on Stack Overflow, on how to get the coordinates of an event on a Canvas Element, relative to the Canvas itself. I'm using the following solution (getEventPosition) and it works well, except from when I add a border to my Canvas:

/**** This solution gives me an offset equal to the border size
 **** when the canvas has a border. Example:
 **** <canvas style='border: 10px solid black; background: #333;' id='gauge_canvas' width='500' height='500'></canvas>
 ****/

// Get DOM element position on page
this.getPosition = function(obj) {
    var x = 0, y = 0;
    if (obj.offsetParent) {
        do {
            x += obj.offsetLeft;
            y += obj.offsetTop;
            obj = obj.offsetParent;
        } while (obj);
    }
    return {'x': x, 'y': y};
};

// Get mouse event position in DOM element (don't know how to use scale yet).
this.getEventPosition = function(e, obj, aux_e, scale) {

    var evt, docX, docY, pos;

    evt = (e ? e : window.event);
    if (evt.pageX || evt.pageY) {
        docX = evt.pageX;
        docY = evt.pageY;
    } else if (evt.clientX || evt.clientY) {
        docX = evt.clientX + document.body.scrollLeft +
            document.documentElement.scrollLeft;
        docY = evt.clientY + document.body.scrollTop +
            document.documentElement.scrollTop;
    }
    // This works on hammer.js
    else if (typeof aux_e !== 'undefined') {
        docX = aux_e.touches[0].x;
        docY = aux_e.touches[0].y;
    }
    pos = this.getPosition(obj);
    if (typeof scale === 'undefined') {
        scale = 1;
    }
    return {'x': (docX - pos.x) / scale, 'y': (docY - pos.y) / scale};
};

Since this code belongs to my library and can take whatever canvas element an user gives it, when an user gives the library a bordered canvas, things break up. Is there a solution taking borders in account?

like image 653
janesconference Avatar asked Sep 09 '12 19:09

janesconference


People also ask

How to get the coordinates of a mouse click on canvas?

- GeeksforGeeks How to get the coordinates of a mouse click on a canvas element ? The coordinates of the mouse whenever a click takes place can be found by detecting the click event with an event listener and finding the event’s x and y position. A function is created which takes in the canvas element and event as parameters.

How do you fill a canvas with coordinates in HTML?

The HTML canvas is a two-dimensional grid. The upper-left corner of the canvas has the coordinates (0,0) In the previous chapter, you saw this method used: fillRect(0,0,150,75). This means: Start at the upper-left corner (0,0) and draw a 150x75 pixels rectangle.

How do you find the X and Y coordinates of an event?

The x position of the event is found using the ‘clientX’ property. The x position of the canvas element, i.e. the left side of the rectangle can be found using the ‘left’ property. Similarly, the position of y-coordinate of the click is found by subtracting the event’s y position with the bounding rectangle’s y position.

How do you find the y-coordinate of a click in HTML?

Similarly, the position of y-coordinate of the click is found by subtracting the event’s y position with the bounding rectangle’s y position. The y-position of the event is found using the ‘clientY’ property.


1 Answers

Here's what I've been using for my latest experimentation.

http://jsfiddle.net/simonsarris/te8GQ/5/

var stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(can, undefined)['paddingLeft'], 10) || 0;
var stylePaddingTop = parseInt(document.defaultView.getComputedStyle(can, undefined)['paddingTop'], 10) || 0;
var styleBorderLeft = parseInt(document.defaultView.getComputedStyle(can, undefined)['borderLeftWidth'], 10) || 0;
var styleBorderTop = parseInt(document.defaultView.getComputedStyle(can, undefined)['borderTopWidth'], 10) || 0;
var html = document.body.parentNode;
var htmlTop = html.offsetTop;
var htmlLeft = html.offsetLeft;

function getMouse(e) {
    var element = can,
        offsetX = 0,
        offsetY = 0,
        mx, my;

    // Compute the total offset
    if (element.offsetParent !== undefined) {
        do {
            offsetX += element.offsetLeft;
            offsetY += element.offsetTop;
        } while ((element = element.offsetParent));
    }

    // Add padding and border style widths to offset
    // Also add the <html> offsets in case there's a position:fixed bar
    offsetX += stylePaddingLeft + styleBorderLeft + htmlLeft;
    offsetY += stylePaddingTop + styleBorderTop + htmlTop;

    mx = e.pageX - offsetX;
    my = e.pageY - offsetY;

    // We return a simple javascript object (a hash) with x and y defined
    return {
        x: mx,
        y: my
    };
}

It works with any border and padding and also works on pages that shim in an object that offsets the HTML (like the stumbleupon bar). It also works if the browser is zoomed.

It seems to work fine on touch devices too.

like image 195
Simon Sarris Avatar answered Oct 26 '22 12:10

Simon Sarris