我正在使用 HTML5 Canvas 构建类似于 Google map 的 map 。我还创建了一个平铺系统,其中只有在屏幕上拖动时才会加载平铺。
所以我有多个将在 Canvas 上绘制的 javascript 文件,每个文件都是一个图 block 。其中一个文件可能如下所示(ctx 是 Canvas 2d 上下文):
ctx.fillStyle="rgb(255,255,255)";
ctx.beginPath();
ctx.moveTo(256,197);
ctx.lineTo(177,241);
ctx.fill();
现在,我知道了一种调用和执行 javascript 文件的方法,如下所示:
function getTile(src){
var tileScript = document.createElement('script');
tileScript.src = src;
var head = document.getElementsByTagName('head')[0];
head.appendChild(tileScript); }
但我真的不希望将大量脚本标记添加到文档头部。对于 map 中的所有图层,这可能最终会变成荒谬的脚本数量,例如 50 个。
是否有另一种读取和执行这些文件的方法?或者,如果有人可以提出一个完全更好的方法来解决这个问题,我会乐于接受建议。
最佳答案
如果您只需要坐标,请使用 Ajax读取 .json
文件。然后你可以用你的数据执行上面的函数。
JSON 示例:
[[784,457],[759,989]] <- your coordinates
Ajax 调用:
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();
}
render()
函数:
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();
}
或者如果你真的只想评估你的函数,执行 Ajax 响应上的 eval() 函数:
eval(xmlhttp.responseText);
但请记住,这是非常不确定的!
关于javascript - 读取javascript文件并执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23585416/