画在画布上用咖啡脚本

时间:2011-07-29 02:34:05

标签: canvas scope coffeescript

我有两个文件

tools.coffee

tools = {}

tools.pencil = =>
  @.started = false

  @.mousedown = (e) =>
    c.begin()
    c.moveTo(e._x, e._y)
    @.started = true

  @.mousemove = (e) =>
    if @.started
      c.lineTo(e._x, e._y)
      c.stroke()

  @.mouseup = (e) =>
    if @.started
      @.started = false

script.coffee

find_position = (obj) ->
  curleft = 0
  curtop = 0
  curleft = $(obj).offset().left - $(window).scrollLeft()
  curtop = $(obj).offset().top - $(window).scrollTop();
  { x: curleft, y: curtop };

init = ->
  window.canvas = $('#drawn').get(0)
  c = canvas.getContext('2d')
  c.lineJoin = "round";
  c.lineCap = "round";
  c.strokeStyle = "#"+ghex;
  c.lineWidth = 1;
  tool = tools.pencil
  $('#container canvas').bind('mousedown mousemove mouseup', mouse_draw);

mouse_draw = (e) ->
  position = find_position(this)
  e._x = e.clientX - position.x;
  e._y = e.clientY - position.y;
  func = tool[e.type];
  console.log tools
  tools.pencil(e)

$(window).ready =>
  init()

如果您无法分辨,代码的要点是在canvas元素上绘制。在过去的几天里,我一直试图让这个工作起作用,我还没有走得太远。我学到的东西是,

tools.pencil已定义但没有铅笔方法。我无法弄清楚为什么会这样。

感谢您的帮助,我认为它只与coffeescript内置的范围有关。

1 个答案:

答案 0 :(得分:3)

原因是这一行:

tools.pencil = =>
  ...

“胖箭头”将函数绑定到this的当前值。那将是全球范围。

使用“细箭头”(->)不会执行功能绑定,因此应该会产生预期的结果。

你可能会考虑这样的事情:

class Pencil
  started: false
  mousedown: (e) -> ...
  ... etc

tools =
  pencil: new Pencil()