Skip to content

Instantly share code, notes, and snippets.

@theel0ja
Forked from Esmala/index.html
Created July 30, 2017 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theel0ja/31ef4637e2289d7cb2bed0c8f19917cb to your computer and use it in GitHub Desktop.
Save theel0ja/31ef4637e2289d7cb2bed0c8f19917cb to your computer and use it in GitHub Desktop.
Shep's simplistic city building game
{"Object1": {"Width": "40","Height": "40", "Color": "blue", "Left": "0", "Top": "0"}, "Object2": {"Width": "40", "Height": "40", "Color": "red", "Left": "100", "Top": "100"}}
// Function to draw object
function drawObject(ctx, left, top, size1, size2, fillcolour) {
ctx.beginPath();
ctx.rect(left, top, size1, size2);
ctx.fillStyle = fillcolour;
ctx.fill();
}
// Function to update view
function updateView(ctx, jsonData) {
var gameData = JSON.parse(jsonData, (key, objectData) => {
// key = Object1, etc.
document.getElementById("myCanvas").innerHTML = drawObject(ctx, objectData.Left, objectData.Top, objectData.Width, objectData.Height, objectData.Color);
return objectData; // return the unchanged property value.
});
}
// Update view using JSON
function updateWithJson(ctx, url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Update view with current json
updateView(ctx, this.responseText);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
<!DOCTYPE html>
<html>
<body>
<center>
<canvas id="myCanvas" width="1000" height="1000" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</center>
<!-- Include functions -->
<script src="functions.js"></script>
<!-- The Game -->
<script>
var c = document.getElementById("myCanvas")
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.rect(0, 0, 1000, 1000);
ctx.fillStyle = "#1ac600";
ctx.fill();
updateWithJson(ctx, "example.json");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment