Browser event and coordinates

From JSXGraph Wiki
Revision as of 08:23, 27 March 2012 by A WASSERMANN (talk | contribs)

This example shows how to add a point whenever the user clicks on the board. The function getMouseCoords extracts the click coordinates from the event object and returns a JXG.Coords object with the point's coordinates on the board. up() is the event listener attached to the board via board.addHook(). The for loop in the event listener is to check if there is already a point as we don't want to create a point in this case.

The JavaScript Code

var getMouseCoords = function(e) {
        var cPos = board.getCoordsTopLeftCorner(e),
            absPos = JXG.getPosition(e),
            dx = absPos[0]-cPos[0],
            dy = absPos[1]-cPos[1];

        return new JXG.Coords(JXG.COORDS_BY_SCREEN, [dx, dy], board);
    },
    up = function(e) {
        var canCreate = true,
            coords = getMouseCoords(e),
            el;

        for (el in board.objects) {
            if(JXG.isPoint(board.objects[el]) && board.objects[el].hasPoint(coords.scrCoords[1], coords.scrCoords[2])) {
                canCreate = false;
                break;
            }
        }

        if (canCreate) {
            board.create('point', [coords.usrCoords[1], coords.usrCoords[2]]);
        }
    },
    board = JXG.JSXGraph.initBoard('jxgbox', {boundingbox: [-5,5,5,-5], axis: true});

    board.addHook(up, 'mouseup');