now.jsの練習。canvas操作ははじめての共同作業 Canvas編を流用させてもらった。
now.jsは単に呼び出せば非同期メッセージングができるようになるので便利ですね。あと実際に使ってみて楽だなぁと感じたのがjade、これはヤバイ。Pythonだと何が一番近いんだろうか?後で探してみよう。
expressコマンドでできたスキャフォールド
$ tree
.
├── app.js
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ │ └── client.js
│ └── stylesheets
│ └── style.css
└── views
├── index.jade
└── layout.jade
app.js
最後の二行追加したくらい。楽ちん
var express = require('express');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', function(req, res){
res.render('index', {
title: 'Express'
});
});
app.listen(3000);
var everyone = require("now").initialize(app);
everyone.now.distributeMessage = function(message){
everyone.now.receiveMessage(message);
};
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
package.json
で依存モジュールがさくっとインストールされるので便利ですね。
{
"name": "application-name"
, "version": "0.0.1"
, "private": true
, "dependencies": {
"express": "2.4.3"
, "jade": ">= 0.0.1"
, "now": ">= 0.0.1"
}
}
client.jsのmove
now.distributeMessage(JSON.stringify(points));
だけで、他のクライアントに通知されます。
Painter.prototype.move = function(event) {
if (!this.isDrawing) {
return;
}
var points = {
bx: this.beforeX,
by: this.beforeY,
ax: event.clientX - 10,
ay: event.clientY - 10,
c: this.strokeStyle
};
now.distributeMessage(JSON.stringify(points));
this.drawLine(points);
this.beforeX = points.ax;
this.beforeY = points.ay;
};
layout.jade
!!! 5
html
head
meta(charset='UTF-8')
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body!= body
index.jade
canvas(id='layer0', class='canvas', style='position: absolute; top: 0; left: 0; border: 10px solid #dddddd;', width='900px', height='600px')
script(src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js')
script(type='text/javascript', src='/javascripts/client.js')
script(src='/nowjs/now.js')
script
$(document).ready(function(){
var painter = new Painter('layer0');
now.receiveMessage = function(message){
var d = JSON.parse(message);
painter.drawLine(d);
}});