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
| var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); var buildings = [ {id: "Airport", x: 50, y:50, w:64, h:64, sx:0, sy:0}, {id: "Bank", x: 150, y:50, w:64, h:64, sx:100, sy:0}, {id: "CarRepair", x: 250, y:50, w:64, h:64, sx:200, sy:0}, {id: "GasStation", x: 50, y:150, w:64, h:64, sx:300, sy:0}, {id: "Hospital", x: 150, y:150, w:64, h:64, sx:400, sy:0}, {id: "Temple", x: 250, y:150, w:64, h:64, sx:500, sy:0}, ];
var bgImage = new Image(); bgImage.src = 'images/background.png';
var buildingImage = new Image(); buildingImage.src = 'images/buildings.png';
buildingImage.onload = function () { ctx.drawImage(bgImage, 0, 0); for (var i = 0; i < buildings.length; i++) { var b = buildings[i]; ctx.drawImage(buildingImage, b.sx, b.sy, b.w, b.h, b.x, b.y, b.w, b.h); } };
document.addEventListener('click', function (e) { var mouseX = e.clientX - ctx.canvas.offsetLeft; var mouseY = e.clientY - ctx.canvas.offsetTop;
for (var i = 0; i < buildings.length; i++) { var bData = buildings[i]; if ( mouseX >= bData.x && mouseX < bData.x + bData.w && mouseY >= bData.y && mouseY < bData.y + bData.h ) { ctx.clearRect(100, 260, 200, 30); ctx.fillStyle = 'yellow'; ctx.fillRect(100, 260, 200, 30);
ctx.fillStyle = '#6495ED'; ctx.textAlign = 'center'; ctx.font = 'bold 20px Arial, sans-serif'; ctx.fillText(bData.id, 200, 280); } } })
|