Question

I'm making a simple game with AngularJS and I wanted to add a canvas to the game. I never used it before and I'm still learning. I don't know how to do the following:

I made a grid to be easier to look at it. So what I want is when the user click on a rectangle, that rectangle should be filled with a color.

   var builder = function () {
    var build_canvas = document.getElementById("builder-canvas");
    var build_context = build_canvas.getContext("2d");

    var x;
    for (x = 0.5; x <= 800; x += 15) {
        build_context.moveTo(x, 0);
        build_context.lineTo(x, 390);
    }

    var y;
    for (y = 0.5; y < 400; y += 10) {
        build_context.moveTo(0, y);
        build_context.lineTo(796, y);
    }

    build_context.strokeStyle = "#000000";
    build_context.stroke();
};
builder();

Here is a fiddle: http://jsfiddle.net/JQd4j/

Thank you in advance.

Was it helpful?

Solution

Simply quantize the x and y values you get from mouse position on click:

build_canvas.onclick = function(e) {
    var rect = build_canvas.getBoundingClientRect(), // canvas abs. position
        x = e.clientX - rect.left,                   // relative x to canvas
        y = e.clientY - rect.top;                    // relative y to canvas

    x = ((x / 15)|0) * 15;                           // quantize x by 15
    y = ((y / 10)|0) * 10;                           // quantize y by 10

    build_context.fillRect(x+1, y+1, 14, 9);         // fill rectangle
}

This quantizing does:

(x / 15)|0

divide by 15 and remove fraction. Then multiply it up again by the same number to get the start position of the cell:

((x / 15)|0) * 15

and the same for y.

Modified fiddle

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