将功能内容移动到外部文件

时间:2014-05-10 21:21:41

标签: javascript html ajax json canvas

我在HTML5画布上使用kinetic.js。我创建了一个形状如此的图层:

var layer = new Kinetic.Layer();
var tile = new Kinetic.Shape({
  sceneFunc: function(context) {
    context.fillStyle="rgb(255,255,255)";
    context.beginPath();
    context.moveTo(256,197);
    context.lineTo(177,241);
    context.bezierCurveTo(172,237,167,232,162,228);
    context.lineTo(0,100);
    context.fill();
  }
});
layer.add(tile);

现在我需要将sceneFunc中的所有内容移动到外部文件中。将会有很多这些文件具有不同的形状。然后我需要能够加载外部文件并在sceneFunc内执行代码。如:

var layer = new Kinetic.Layer();
var tile = new Kinetic.Shape({
  sceneFunc: function(context) {
    //call and execute shape code here
  }
});
layer.add(tile);

将以下代码放在单独的文件中:

context.fillStyle="rgb(255,255,255)";
context.beginPath();
context.moveTo(256,197);
context.lineTo(177,241);
context.bezierCurveTo(172,237,167,232,162,228);
context.lineTo(0,100);
context.fill();

有没有办法做到这一点?我知道我可以创建外部文件的脚本标记,但这将执行sceneFunc函数之外的代码。使用XMLHttpRequest的ajax调用并使用eval();

解析它也是如此

如何从外部文件中读取代码,然后在正确的位置执行?!

1 个答案:

答案 0 :(得分:0)

你不能完全按照自己的意愿去做,但你可以这样做:

创建一个形状函数数组

var shapes=[];

然后在小文件中有类似

的内容
shapes.push(function(context){
  context.fillStyle="rgb(255,255,255)";
  // shape drawing code here
});

使用<script>标记在数组声明后加载小文件,然后在sceneFunc中执行类似

的操作
shapes.forEach(function(shape) {
  shape(context);
});

您可以使用XHR和eval执行类似的操作(在这种情况下,您可以通过编程方式添加“shapes.push”内容而不是将其放在小文件中),但是您只需要异步调用形状创建时所有形状都已加载。