TOP   CoffeeScript

CoffeeScript Sample

サンプルコード

もとの JavaScript のコードはこれです。

HTML

<canvas id="Canvas"></canvas>
<br>
<div class="ms" style="color: blue;">クリックして下さい</div>
<form>
<div class="ms"><input type="button" value="消去" onclick="cvsClear();"></div>
</form>
   
<script type="text/coffeescript">
....
</script>

CoffeeScript

wd = cvs = ctx = r = num = null

Circle = ->
  @dist = (c)->
    Math.sqrt(@o.sub(c.o).absl2())
  null

Vector = (x, y)->
  @x = x; @y = y
  @mul = (a)->
    new Vector(a * @x, a * @y)
  @innPro = (v)->
    @x * v.x + @y * v.y
  @add = (v)->
    new Vector(@x + v.x, @y + v.y)
  @sub = (v)->
    new Vector(@x - v.x, @y - v.y)
  @absl2 = ->
    Math.pow(@x, 2) + Math.pow(@y, 2)
  null

cir = []
wd = 500; r = 20; num = 0
$(window).load ->
  cvs = document.getElementById("Canvas"); ctx = cvs.getContext("2d")
  cvs.height = wd; cvs.width = wd
  $(cvs).click (e)-> setBall(e)
  setInterval(f, 10)
  return

f = ->
  return if num == 0
  ctx.clearRect(0, 0, wd, wd)
  fl = geneArray(num)
  for i in [0...num]
    ctx.beginPath()
    ctx.fillStyle = cir[i].cl
    ctx.arc(cir[i].o.x, cir[i].o.y, r, 0, Math.PI * 2)
    ctx.fill()
    cir[i].o = (cir[i].o).add(cir[i].v)
    if cir[i].o.x >= wd - r || cir[i].o.x <= r
      cir[i].v.x = -cir[i].v.x
    else
      if cir[i].o.y >= wd - r || cir[i].o.y <= r
        cir[i].v.y = -cir[i].v.y
    for j in [0...num]
      continue if !fl[i][j]
      c1 = cir[i]; c2 = cir[j]
      if c1.dist(c2) <= r * 2
        v1 = c1.v; v2 = c2.v
        ra = c1.o.sub(c2.o)
        tmp = ra.mul(ra.innPro(v1.sub(v2)) / ra.absl2())
        c1.v = v1.sub(tmp)
        c2.v = v2.add(tmp)
        fl[i][j] = false
  return

geneArray = (n)->
  a = new Array(n)
  for i in [0...n]
    a[i] = new Array(n)
    for j in [0...n]
      a[i][j] = true
      a[i][j] = false if i <= j
  a

setBall = (e)->
  x1 = e.pageX - cvs.offsetLeft; y1 = e.pageY - cvs.offsetTop
  return if x1 <= r || x1 >= wd - r || y1 <= r || y1 >= wd - r
  num++
  cir[num - 1] = new Circle()
  cir[num - 1].o = new Vector(x1, y1)
  cir[num - 1].v = new Vector((Math.random() * 2 + 2) * (Math.random() - 0.5) * 2,
                (Math.random() * 2 + 2) * (Math.random() - 0.5) * 2)
  cir[num - 1].cl = "rgb(" + rnd() + "," + rnd() + "," + rnd() + ")"
  if near(num - 1)
    num--
    pop(cir)
  return

near = (i)->
  return false if i == 0
  for j in [0...i]
    return true if cir[i].dist(cir[j]) <= r * 2
  false

rnd = ->
  String(Math.floor(Math.random()*256))

window.cvsClear = ->
  ctx.clearRect(0, 0, wd, wd)
  num = 0
  return

気をつけるべきは、関数の最後の値が必ず返されてしまうので、不必要なところは return を明示的に書くか、null などを最後に置くということ。
それから、HTML から例えばボタンで CoffeeScript を呼び出す場合、CoffeeScript の全体は即時関数でラップされるので、呼び出される関数の頭に "window." を付けておくこと。




inserted by FC2 system