LiveScript ImageData最近邻插值(Nearest-neighbor interpolation)图像缩放算法

浅析 HTML5 Canvas 的几种中文字体缩小方案》中用到的最近邻插值算法的LiveScript实现.

require! 'prelude-ls': {round, map, zip-with}

nearest-neighbor-interpolation = (zoom, src-image) ->
  color = (image, x, y) ->
    i = (y * image.width + x) * 4
    map (|| 0), image.data[i to i + 3]

  canvas = document.create-element \canvas
  canvas.width = src-image.width * zoom
  canvas.height = src-image.height * zoom
  ctx = canvas.get-context \2d
  dst-image= ctx.create-image-data canvas.width, canvas.height
  for dst-x from 0 til canvas.width
    for dst-y from 0 til canvas.height
      src-color = color src-image, (round dst-x / zoom), (round dst-y / zoom)
      dst-i = (dst-y * canvas.width + dst-x) * 4
      dst-color = map (/ 2), zip-with (+), src-color, color dst-image, dst-x, dst-y
      for i from 0 to 3
        dst-image.data[dst-i + i] = dst-color[i]
  ctx.put-image-data dst-image, 0, 0
  canvas