Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 87 lines (63 sloc) 2.199 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Example 12 - (Capturing click events and translating them to matrix coordinates)</title>

<script>

window.onload = function () {
var grid = {
width: 10,
height: 10
}

var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');

var tileMap = [];

var tile = new Image();
tile.src = "../img/tile.png";

var dirt = new Image();
dirt.src = "../img/dirt.png";

canvas.addEventListener('mousedown', handleMouseDown, false);

draw();

function handleMouseDown(e) {
var gridOffsetY = 0;
var gridOffsetX = 0;

// Take into account the offset on the X axis caused by centering the grid horizontally
gridOffsetX += (canvas.width / 2) - (tile.width / 2);

var col = (e.clientY - gridOffsetY) * 2;
col = ((gridOffsetX + col) - e.clientX) / 2;

var row = ((e.clientX + col) - tile.height) - gridOffsetX;

row = Math.round(row / tile.height);
col = Math.round(col / tile.height);

// Check the boundaries!
if (row >= 0 &&
col >= 0 &&
row <= grid.width &&
col <= grid.height) {

tileMap[row] = (tileMap[row] === undefined) ? [] : tileMap[row];

tileMap[row][col] = 1;
draw();
}
}


function draw() {

c.clearRect (0, 0, canvas.width, canvas.height);

for (var row = 0; row < grid.width; row++) {
for (var col = 0; col < grid.height; col++) {

var tilePositionX = (row - col) * tile.height;

// Center the grid horizontally
tilePositionX += (canvas.width / 2) - (tile.width / 2);

var tilePositionY = (row + col) * (tile.height / 2);

if (tileMap[row] != null && tileMap[row][col] != null) {
c.drawImage(dirt, Math.round(tilePositionX), Math.round(tilePositionY), dirt.width, dirt.height);
} else {
c.drawImage(tile, Math.round(tilePositionX), Math.round(tilePositionY), tile.width, tile.height);
}
}
}
}
}
</script>
    </head>
    <body>
<canvas id="myCanvas" width="600" height="300"></canvas>
    </body>
</html>
Something went wrong with that request. Please try again.