请解释此代码段

时间:2010-11-09 05:02:35

标签: javascript html5

我在浏览html5画布示例时遇到了这段代码。 我已粘贴代码,我在有疑问的地方发表了评论。

if(window.addEventListener) {

  window.addEventListener('load', function () {
  var canvas, context, tool;

  function init () {
    canvas = document.getElementById('imageView');
    if (!canvas) {
      alert('Error: I cannot find the canvas element!');
      return;
    }

    if (!canvas.getContext) {
      alert('Error: no canvas.getContext!');
      return;
    }

     context = canvas.getContext('2d');
    if (!context) {
      alert('Error: failed to getContext!');
      return;
    }

        tool = new tool_pencil();

    canvas.addEventListener('mousedown', ev_canvas, false);
    canvas.addEventListener('mousemove', ev_canvas, false);
    canvas.addEventListener('mouseup',   ev_canvas, false);
  }

   function tool_pencil () {
    var tool = this;
    this.started = false;


    this.mousedown = function (ev) {
        context.beginPath();
        context.moveTo(ev._x, ev._y);
        tool.started = true;
    };

      this.mousemove = function (ev) {
      if (tool.started) {
        context.lineTo(ev._x, ev._y);
        context.stroke();
      }
    };

       this.mouseup = function (ev) {
      if (tool.started) {
        tool.mousemove(ev);
        tool.started = false;
      }
    };
  }

    function ev_canvas (ev) {
    if (ev.layerX || ev.layerX == 0) { 
      ev._x = ev.layerX;
      ev._y = ev.layerY;
    } else if (ev.offsetX || ev.offsetX == 0) { 
      ev._x = ev.offsetX;
      ev._y = ev.offsetY;
    }

    //Please explain the follwing set of line
    var func = tool[ev.type];
    if (func) {
      func(ev);
    }
  }

  init();

}, false); }

3 个答案:

答案 0 :(得分:3)

结合其他答案,它正在做的是将所有回调放在一个对象中。结果是functool.onmousedowntool.onmouseup等。

答案 1 :(得分:1)

//Please explain the follwing set of line
var func = tool[ev.type]; // Set func to the tool object's member 
                          // named 'event.type' 
                          // Will set func to undefined if no function is 
                          // found in the tool object
if (func) {  // if a func was found then call it.
  func(ev);
}

请注意,tool哈希对象用于保存函数引用,而不是标量,如1,“字符串”等.Javascript的一个特性是您可以在运行时创建,保存,传递函数

已添加感谢@Chris Morgan指出an_obj ['unknown_key'] == undefined,而不是null。

另请注意,foo ['a_key']是说foo.a_key的运行时方式 - 对象'foo'的'a_key'成员。

最后,Javascript没有哈希值。它具有与其他语言中的Hash类型相当好的对象。

添加了更多(查看了所有代码后,而不仅仅是相关部分)。代码正在创建一个对象tool。它有许多成员:

  • started flag
  • mousedownmouseupmousemove函数

代码片段试图找到与事件类型匹配的函数。所以在这种情况下,对象tool被用作对象,而不是哈希。我已适当更新了答案的第一部分。

答案 2 :(得分:0)

看起来它正在尝试将ev.type类型的“工具”分配给变量func。这应该是一个功能。然后它检查函数是否存在(即,是否已分配)并调用它,如果是,则将ev变量作为参数传递。