I'm building a map similar to Google Maps using HTML5 canvas. I'm also creating a tiling system where tiles are only loaded when dragged on screen.
So I have multiple javascript files that will draw on the canvas, each one a tile. One of the files might look like this (ctx being the canvas 2d context):
ctx.fillStyle="rgb(255,255,255)";
ctx.beginPath();
ctx.moveTo(256,197);
ctx.lineTo(177,241);
ctx.fill();
Now, I know one method of calling and executing the javascript files, which is like so:
function getTile(src){
var tileScript = document.createElement('script');
tileScript.src = src;
var head = document.getElementsByTagName('head')[0];
head.appendChild(tileScript); }
But I don't really want large numbers of script tags being added to the document head. With all the layers in the map, this might end up being a ridiculous number of scripts like 50.
Is there another method of reading and executing these files? Alternatively, if anyone could suggest an entirely better method of going about this, I would be open to suggestions.
If you just need the coordinates, use Ajax to read a .json
File. Then you could execute the function above with your data.
JSON Example:
[[784,457],[759,989]] <- your coordinates
Ajax call:
function loadJSON() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
render(xmlhttp.responseText) //render your map with the response
}
}
xmlhttp.open("GET", "your_json_file.json", true);
xmlhttp.send();
}
The render()
function:
function render(response){
var json = JSON.parse(response); //parse the response to json
ctx.fillStyle="rgb(255,255,255)";
ctx.beginPath();
ctx.moveTo(json[0][0],json[0][1]);
ctx.lineTo(json[1][0],json[1][1]);
ctx.fill();
}
Or if you realy just want to eval your functions, execute the eval() function on your Ajax Response:
eval(xmlhttp.responseText);
but remember that this is very uncertain!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.