Question

If I created a virtual grid 32x32 as a <div> example:

enter image description here

I want to fill one of the tile with a black box on click I have so far this:

var _proto = {
    id:0,
    x:0,
    y:0
}

var objects = [];

$(".test").on("mousedown", function(e) {

    var offset = $(this).offset();
    var prex2 = 0, prey2 = 0;

    prex2 = _proto.x = e.pageX-offset.left;
    prey2 = _proto.y = e.pageY-offset.top;
    _proto.id = (_objects.length)?_objects[_objects.length-1].id+1:0;

    // Add to grid (not sure how to get proper cordinates)
    $("<div style='display:absolute;width:32px;height:32px;background:black'></div>")
        .css("top","")
        .css("left","")
        .appendTo("#maindiv");

});

I have the coordinates as prex2, and prey2 where the user clicked, but how do I know where to put it in the grid? I'm sure there a simple math equation but I can't figure it out.

Was it helpful?

Solution

Here's a snippet from a map editor that I was working on a few months back. It might help you grapple with your own code.

mapBlanket.addEventListener("mousedown", function(e) {
    var sideWidth = document.getElementById("mapSide").offsetWidth;
    var headHeight = document.getElementById("system").offsetHeight + 32;
    var clickX = e.pageX - mapBlanket.offsetLeft - sideWidth + mapBlanket.parentNode.scrollLeft;
    var clickY = e.pageY - mapBlanket.offsetTop - headHeight + mapBlanket.parentNode.scrollTop;
    var tileX = clickX - (clickX % map.grid);
    var tileY = clickY - (clickY % map.grid);
    if (paintOn == 5) {
        eventThis(tileX, tileY);
    } else if (paintOn < 5) {
        paintThis(tileX, tileY);
    }
    ...
}

For reference, the map.grid was 32, same as yours. I just had a good bit defined in an object at the top of the file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top