Drkcore

25 08 2011 javascript Tweet

CoffeeScriptとjQueryを一緒に使ってみる

作付け状況をcanvasを使って表示するやつをExpress+Jade+CoffeeScript+jQueryという構成でやってみた。以前書いたやつは単にCanvasの練習を兼ねたものだったが、今回はデータをAjaxでとってきて描画することにした。

node_allot

サーバー側はExpressで。expressコマンドでスケルトン生成してくれるので地味に便利すぎですね。ちょっと試して終ったら消せるので心理的負担も少ない。coffeescriptのスケルトンを出力するオプションで切り替えられるようになっているとさらに嬉しいかもとおもったけどあるのかな?

express allot
cd allot
npm install -d

これでスケルトンが作られるのでapp.jsとviews/index.jadeを書き換える

app.js

/jsonにアクセスしたらデータをJSONで返すようにする。

// Routes

app.get('/', function(req, res){
  res.render('index', {
    title: 'Express'
  });
});

app.get('/json', function(req, res){
  var allotment_data = [
    {name:"なにもうえてない",  x:10,  y:10,  width:480, height:120, color:"#CCCCCC"},
    {name:"浅葱",  x:10,  y:140,  width:140, height:120, color:"#66CC66"},
    {name:"ニンニク",  x:160,  y:140,  width:80, height:120, color:"#993300"},
    {name:"春菊",  x:250,  y:140,  width:80, height:120, color:"#339933"},
    {name:"ジャガイモ",  x:340,  y:140,  width:150, height:120, color:"#CC6600"},
    {name:"ソラマメ",  x:10,  y:340,  width:70, height:150, color:"#339933"},
    {name:"エンドウ",  x:10,  y:270,  width:70, height:60, color:"#339933"},
    {name:"ジャガイモ",  x:90,  y:270,  width:400, height:110, color:"#CC6600"},
    {name:"ミョウガ",  x:90,  y:390,  width:400, height:100, color:"#CC9966"}
  ];

  res.send(JSON.stringify(allotment_data));
});

views/index.jade

h1= title
canvas#allotment(width=500, height=500)
script(type="text/javascript", src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js")
script(type="text/javascript", src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js")
script(type="text/coffeescript")
  | draw = () ->
  |   $.getJSON('/json', (data) -> drawCanvas(data))
  | 
  | drawCanvas = (allotment_data) ->
  |   ctx = document.getElementById('allotment').getContext('2d')
  |   ctx.save()
  |   ctx.font = "20px"
  |   for alt in allotment_data
  |     ctx.fillStyle = alt.color
  |     ctx.fillRect( alt.x, alt.y, alt.width, alt.height)
  |     ctx.fillStyle = "#000"
  |     ctx.fillText(alt.name, 12 + alt.x, 32 + alt.y)
  |   ctx.restore()
  | 
  | draw()

もとのと比べるとcoffeescriptのコードのほうがシンプルで見やすくなっていいですね。普段Python使っているのでインデントはわかりやすいし、for in ループはpythonそのものだし、文の終わりに;が必要ないのもいい。

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021