-
Notifications
You must be signed in to change notification settings - Fork 78
/
ex13-isogrid-buildings.html
89 lines (65 loc) · 2.23 KB
/
ex13-isogrid-buildings.html
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
88
89
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Example 13 - (Placing buildings)</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 building = new Image();
building.src = "../img/icecream.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 < 10; row++) {
for (var col = 0; col < 10; 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) {
tilePositionY -= building.height - tile.height;
tilePositionX -= (building.width / 2) - (tile.width / 2);
c.drawImage(building, Math.round(tilePositionX), Math.round(tilePositionY), building.width, building.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>