user1457307
user1457307

Reputation: 1

Canvas drawing errors (HTML5 and JavaScript)

I can usually research my problem and get an answer from someone else's mistake but this time i am having a rather unusual time finding an answer. The concept is that you can colorize 32x32 "pixels" on a 16x16 grid. My complete code follows:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="jscolor.js"></script>
    <title>Tiles</title>
</head>
<body>
    <canvas id="canvas" height="512" width="512" onclick="draw(window.event)">
        Oops, you don't have Canvases
    </canvas>
    <input type="text" value="000000" class="color"></input>
    <script type="text/javascript">
        var draw_a = document.getElementById("canvas").getContext("2d");
        function draw(e) {
            draw_a.fillStyle = "#" + document.getElementById("color").value;
            draw_a.fillRect(
                math.floor( e.clientX / 16 ),
                math.floor( e.clientX / 16 ),
                32,
                32
            );
        }
        draw_a.fillStyle = "#000000";
        draw_a.fillRect( 0 , 0 , 512 , 512 );
    </script>
</body>
</html>

Upvotes: 0

Views: 204

Answers (1)

Alnitak
Alnitak

Reputation: 340045

You're dividing and rounding the click coordinates, but not multiplying the value back up again to map to canvas coordinates - there should also be 32 pixels between points, not 16.

There's also no such function as math.floor, it should be Math.floor:

var x = 32 * Math.floor(e.clientX / 32);
var y = 32 * Math.floor(e.clientY / 32);
draw_a.fillRect(x, y, 32, 32);

Lastly, your color input should have an id of color, not a class

Working (in Chrome at least) demo at http://jsfiddle.net/alnitak/VJNdR/

Upvotes: 2

Related Questions