d3.js scene controlled by remote data using node.js and socket.io

d3.js is cool. So is node.js. Hence, doing something with both technologies is almost a logical consequence.

Start the Demo at least in two browser instances/devices (tested with Firefox, Chrome, IE9+, iPad, iPhone). Then click to create and to burst bubbles. Drag the bubbles around and try the action buttons to force larger changes to the d3.js scene.

This demo maintains a pool of “circles” on the server and implements the distributed MVC pattern. The Model is kept on the server. Each instance of the browser keeps a copy of the View and the Controller. Furthermore, a lightweight version of the model is used for data presentation and is processed by the d3 engine. The node.js based server is responsible for synchronization of all models via push messages. All user interaction triggers a change on the server model first. This holds true even for the initiating client. An example scenario follows:

  1. user clicks on a bubble
  2. the event handler reads the “id” of the SVG-circle element and calls the server side function remove(id)
  3. the server updates the model
  4. the server calls the removeData(id) function for each connected client (including the initiating one)
  5. the data structure in the client is updated (in this example the object with the specified id is removed)
  6. d3.js scene is updated

The static files (index.html, CSS, templates and Javascript files) are served using express.js. The socket.io library is used as a convenience layer on top of websockets and provides a reliable permanent server/client connection.

Remarks regarding performance issues:

  • the good news: node.js and websockets are blazingly fast, playing with the demo for some minutes in three browser instances generates a CPU usage time for the node.js process of about 5 seconds, i.e. there is plenty of room for more serious stuff
  • advice: use SVG opacity styles instead of HTML opacity styles whenever possible, this reduces the SVG render time and enables larger SVG scenes (10 fold improvement in Firefox)

The source code for the server application is as follows:

// utility library, see: http://underscorejs.org/
var _ = require('underscore');

// initialize web server framework
var express = require('express');
var app = express();
var http = require('http');
http.globalAgent.maxSockets = 500;
var server = http.createServer(app);

var logFile = require('fs').createWriteStream('./circle.log', {flags: 'a'});
app.use(express.logger({stream: logFile}));
app.use(express.compress());
app.use(express.static(__dirname + '/public'));

// websocket
var io = require('socket.io').listen(server, {log: false});

//the circle model
var model = require('./model').model;
model.populate();

// listen on connection event using namespace 'circle'
io.of('/circle').on('connection', function (socket) {
    var address = socket.handshake.address;
    logFile.write("New connection from " + address.address + '\n');
    logFile.write('send circle data: ' + model.getSize() + ' entries' + '\n');

    // any connecting client gets the complete model data
    socket.emit('update', {ts: Date.now(), circles: model.getData()});

    var behaviour = {
		'add': add,
		'remove': remove,
		'resize': resize,
		'moveStart': moveStart,
		'move': move,
		'moveEnd': moveEnd
	};
    // map events to functions
    _.map(behaviour, function(func, eventName) {
        socket.on(eventName, _.bind(func, socket));
    });
});

function add(attr) {
    logFile.write('add circle: x=' + attr.x + ', y=' + attr.y + '\n');
    var entry = model.add(attr);
    io.of('/circle').emit('add', {ts: Date.now(), entry: entry});
}

function remove(id) {
    logFile.write('remove circle: id=' + id + '\n');
    id = model.remove(id);
    if (id != -1)
        io.of('/circle').emit('remove', {ts: Date.now(), id: id});
}

function resize(info) {
    var entry = model.resize(info.id, info.delta);
    if (entry)
    	io.of('/circle').emit('resize', {ts: Date.now(), entry: entry});
}

function moveStart(id) {
    logFile.write('moveStart circle: id=' + id + '\n');
    //socket.broadcast.emit('circles moveStart', {ts: Date.now(), id: id});
    io.of('/circle').emit('moveStart', {ts: Date.now(), id: id});
}

function moveEnd(entry) {
    logFile.write('moveEnd circle: id=' + entry.id + ', x=' + entry.x + ', y=' + entry.y + '\n');
    model.move(entry);
    io.of('/circle').emit('moveEnd', {ts: Date.now(), entry: entry});
}

function move(entry) {
    io.of('/circle').emit('move', {ts: Date.now(), entry: entry});
}

//the job controller
var jobs = require('./jobs').jobs;
// prevent "flooding" the websocket connection with jobs update events
jobs.onChange = _.throttle(function () {
    io.of('/jobs').emit('update', jobs.getData());
}, 333);

//listen on connection event using namespace 'jobs'
io.of('/jobs').on('connection', function (socket) {
    logFile.write('send job list\n');

    // any connecting client gets the complete job data
    socket.emit('update', jobs.getData());

    var behaviour = {
   		'shuffle': shuffle,
   		'stream': stream,
   		'reset': reset
    };
    // map events to functions
    _.map(behaviour, function(func, eventName) {
        socket.on(eventName, _.bind(func, socket));
    });
});

function shuffle() {
    jobs.start('shuffle', function (job) {
        model.shuffle();
        io.of('/circle').emit('update', {ts: Date.now(), circles: model.getData()});
        setTimeout(function () {
            job.complete();
            logFile.write('shuffle completed' + '\n');
        }, 1000);
    });
    logFile.write('shuffle started' + '\n');
}

function stream() {
    var count = 100;
    function streamEvent (job) {
        io.of('/circle').emit('add', {ts: Date.now(), entry: model.add(0, 0)});
        io.of('/circle').emit('remove', {ts: Date.now(), id: model.removeRandom()});
        if (--count) {
            setTimeout(function(){streamEvent(job);}, 150);
            job.running(100 - count);
        } else {
            job.complete();
            logFile.write('stream completed' + '\n');
        }
    }
    jobs.start('stream', streamEvent);
    logFile.write('stream started' + '\n');
}

function reset() {
    jobs.start('reset', function (job) {
        model.populate();
        io.of('/circle').emit('update', {ts: Date.now(), circles: model.getData()});
        setTimeout(function () { job.complete(); }, 600);
        logFile.write('reset' + '\n');
    });
}

// start the server
server.listen(7777, function () {
    logFile.write('circle demo started on port ' + server.address().port + '\n');
});

The server model:

var _ = require('underscore');

// the circle model
exports.model = {
    INIT_CIRCLES: 20,
    SIZE: 450,
    COLORS: ["red","orange","blue","green"],
    nextId: 1,
    data: [],
    random: function(pool) {
        if (_.isFinite(pool)) {
            return (Math.random()*pool)|0;
        }
        if (_.isArray(pool)) {
            return pool[Math.random()*pool.length|0];
        }
        return Math.random();
    },
    getData: function() {
        return this.data;
    },
    getSize: function() {
        return this.data.length;
    },
    getColorStatistics: function() {
        var colors = _.object(this.COLORS, [0, 0, 0, 0]);

        for (var i=0; i< this.data.length; i++) {
            colors[this.data[i].color] += 1;
        }

        return colors;
    },
    add: function(attr) {
        var entry = {
            id: this.nextId++,
            x: attr.x || this.SIZE - 30 - this.random(this.SIZE - 60),
            y: attr.y || this.SIZE - 30 - this.random(this.SIZE - 60),
            r: 30 + this.random(35),
            color: this.random(this.COLORS),
            opacity: (30 + this.random(50))/100
        };
        this.data.push(entry);
         return entry;
    },
    resize: function(id, delta) {
    	var factor = (delta > 0) ? 1.03 : 1/1.03;
        for (var i=0; i< this.data.length; i++) {
        	var d = this.data[i];
            if (d.id == id) {
            	var old = d.r;
                d.r *= factor;
                d.r = Math.min(150, Math.max(20, d.r));
                if (d.r == old)
                	return null;
                else
                	return d;
            }
        }
    },
    move: function(entry) {
        for (var i=0; i< this.data.length; i++) {
        	var d = this.data[i];
            if (d.id == entry.id) {
                d.x = entry.x;
                d.y = entry.y;
                // move to end, emulates highest z-index
                this.data.splice(i, 1);
                this.data.push(d);
                return;
            }
        }
    },
    remove: function(id) {
        for (var i=0; i< this.data.length; i++) {
            if (this.data[i].id == id) {
                this.data.splice(i, 1);
                return id;
            }
        }
        return -1;
    },
    removeRandom: function() {
        if (this.data.length) {
            var i = this.random(this.data.length);
            var id = this.data[i].id;
            this.data.splice(i, 1);
            return id;
        }
        return -1;
    },
    populate: function() {
        this.data = [];
        for (var i=0; i< this.INIT_CIRCLES; i++) {
            this.add({x: 0, y: 0});
        }
    },
    shuffle: function() {
        for (var i=0; i< this.data.length; i++) {
            this.data[i].x = this.SIZE - 30 - this.random(this.SIZE - 60);
            this.data[i].y = this.SIZE - 30 - this.random(this.SIZE - 60);
        }
    }
};

//TODO: normalize size and position data, get rid of pixel related information

The client code:

var CircleController = can.Control({

	isMobile: navigator.userAgent.match(/Mobile/i),

	init: function () {
		var me = this;
		this.eventCount = 0;

		// an array of circle objects
		this.data = [];

		var fragment = can.view('/templates/circle.ejs');
		this.element.html(fragment);			

		this.setupDrawingArea();
		this.setupWebsocket();

		var throttleResize = _.throttle(function (info) { me.socket.emit('resize', info); }, 25);

		this.element.bind('mousewheel', function(event, delta, deltaX, deltaY) {
		    if (event.target.nodeName == 'circle')
		    	throttleResize({id: event.target.getAttribute('id'), delta: delta});
		    event.preventDefault();
		});
	},

	setupDrawingArea: function () {
		var me = this;
	    // setup drawing area
	    this.element.css("width", "450px").css("height", "450px");
	    this.scene = d3.select(this.element.find("svg")[0])
	        .attr("width", 500).attr("height", 500)
	        .on("click", function() {
	            var target = d3.event.target;
	            if (target.nodeName == 'circle') {
	                var id = d3.select(target).attr("id");
	                me.socket.emit('remove', id);
	            } else {
	                var pos = d3.mouse(this);
	                me.socket.emit('add', {x: pos[0]|0, y: pos[1]|0});
	            }
	        });
	},

	enter: function () {
		this.dragging = false;
		var me = this;

		function dragStart() {
			me.dragging = true;
			var circle = d3.select(this);
			var id = circle.attr("id");
			me.socket.emit('moveStart', id);
		};

		function dragMove() {
			var circle = d3.select(this);
			var ev = d3.event;
			circle.attr("cx", ev.dx + parseInt(circle.attr("cx")));
			circle.attr("cy", ev.dy + parseInt(circle.attr("cy")));
			var id = circle.attr("id");
			var x = circle.attr('cx');
			var y = circle.attr('cy');
			me.socket.emit('move', {id: id, x: x, y: y});
		};

		function dragEnd() {
			me.dragging = false;
			var circle = d3.select(this);
			var id = circle.attr("id");
			var x = Math.min(450, Math.max(0, circle.attr('cx')));
			var y = Math.min(450, Math.max(0, circle.attr('cy')));
			me.socket.emit('moveEnd', {id: id, x: x, y: y});
		};

		// macro function
		function P(propName) { return function(d) { return d[propName]; }; }

		// the key function binds the data entries to the DOM elements using the id
		var circles = this.scene.selectAll("circle.default").data(this.data, P("id"));

		circles.enter() // the enter set, a set of new data entries without DOM equivalent
		.append("circle")
		.call(d3.behavior.drag()
				.on('dragstart', dragStart)
				.on('drag', dragMove)
				.on('dragend', dragEnd))
				.attr("id", P("id"))
				.attr("class", "default")
				.attr("r", 1)
				.attr("cx", P("x"))
				.attr("cy", P("y"))
				.style("fill", function(d) { return me.isMobile ? d.color : "url(#gradient_" + d.color + ")"; })
				.style("fill-opacity", P("opacity"))
				.transition().duration(500)
				.attr("r", P("r"));
	},

	exit: function () {
		// macro function
		function P(propName) { return function(d) { return d[propName]; }; }

		var circles = this.scene.selectAll("circle.default").data(this.data, P("id"));

		circles.exit() // the exit set, a set of superfluous DOM nodes without data equivalent
		.attr("class", null)
		.style("stroke-opacity", 0)
		.transition()
		.attr("r", function(d) { return 1.8*d.r; })
		.style("fill-opacity", 0.05)
		.each("end", function () { d3.select(this).remove(); });
	},

	update: function (dur) {
		// macro function
		function P(propName) { return function(d) { return d[propName]; }; }

		var circles = this.scene.selectAll("circle.default").data(this.data, P("id"));

		circles // the update set, all DOM nodes with a data binding
		.transition().duration(dur)
		.attr("r", P("r"))
		.attr("cx", P("x"))
		.attr("cy", P("y"));
	},

	//
	// the payload called as event from server
	//
	setData: function (ts, circles) {
		this.data = JSON.parse(JSON.stringify(circles));
		this.exit();
		this.enter();
		this.update(800);
		this.log(ts, this.data.length + " circles updated");
	},

	addData: function (ts, entry) {
		this.data.push(JSON.parse(JSON.stringify(entry)));
		this.enter();
		this.log(ts, "circle added, id=" + entry.id);
	},

	toForeground: function (d3Node) {
		var node = d3Node[0][0];
		if (!node)
			return;
		node.parentNode.appendChild(node);
	},

	moveStart: function (ts, id) {
		if (this.dragging)
			return;
		var circle = this.scene.select('circle[id="' + id + '"]');
		circle.style("stroke", "white");
		this.toForeground(circle);
	},

	moveEnd: function (ts, entry) {
		this.log(ts, "circle moved, id=" + entry.id);
		for (var i=0; i < this.data.length; i++) {
			if (this.data[i].id == entry.id) {
				this.data[i].x = entry.x;
				this.data[i].y = entry.y;
				break;
			}
		}
		var circle = this.scene.select('circle[id="' + entry.id + '"]');
		circle.style("stroke", null);
		this.toForeground(circle);
		this.update(300);
	},

	move: function (ts, entry) {
		if (this.dragging)
			return;
		this.log(ts, "circle moving, id=" + entry.id);
		var circle = this.scene.select('circle[id="' + entry.id+ '"]');
		circle.attr("cx", entry.x).attr("cy", entry.y);
	},

	resize: function (ts, entry) {
		this.log(ts, "circle resize, id=" + entry.id);
		for (var i=0; i < this.data.length; i++) {
			if (this.data[i].id == entry.id) {
				this.data[i].r = entry.r;
				break;
			}
		}
		var circle = this.scene.select('circle[id="' + entry.id+ '"]');
		circle.attr("r", entry.r);
	},

	removeData: function (ts, id) {
		for (var i=0; i < this.data.length; i++) {
			if (this.data[i].id == id) {
				this.data.splice(i, 1);
				break;
			}
		}
		this.exit();
		this.log(ts, "circle removed, id=" + id);
	},

	format: d3.time.format("%X"),

	log: function (ts, msg) {
        var fragment = this.eventCount + " circle events, " + msg + ' @' + this.format(new Date(ts)) + ' +' + ts%1000 + 'ms';
        $('#log').html(fragment);
	},

	setupWebsocket: function () {
		var me = this;

	    // map events to functions
	    var behaviour = {
	        'update': function (data) {
	            me.eventCount++;
	            me.setData(data.ts, data.circles);
	        },
	        'add': function (data) {
	            me.eventCount++;
	            me.addData(data.ts, data.entry);
	        },
	        'resize': function (data) {
	            me.eventCount++;
	            me.resize(data.ts, data.entry);
	        },
	        'remove': function (data) {
	            me.eventCount++;
	            me.removeData(data.ts, data.id);
	        },
	        'moveStart': function (data) {
	        	me.eventCount++;
	        	me.moveStart(data.ts, data.id);
	        },
	        'move': function (data) {
	        	me.eventCount++;
	        	me.move(data.ts, data.entry);
	        },
	        'moveEnd': function (data) {
	            me.eventCount++;
	            me.moveEnd(data.ts, data.entry);
	        }
	    };

	    // connect with websocket server using namespace: '/circle'
	    this.socket = io.connect('/circle'); 

    	_.map(behaviour, function(func, eventName) {
    		me.socket.on(eventName, func);
    	});
	 }
});

complete source code as tar file

Posted in d3.js, node.js | Tagged , | Leave a comment

Lupe mit Kamerafunktion

Ein jQuery-Beispiel aus der Kategorie Fingerübungen. In dieser Kategorie werde ich in unregelmässigen Abständen Code-Schnippsel oder Mini-Applikationen veröffentlichen die es wahrscheinlich nie zu eigenen Projektstatus schaffen werden, aber trotzdem einige Aspekte enthalten die es Wert sind aufgeschrieben zu werden.

Dieses kleine Demo ist ein gutes Beispiel für die Ausdruckskraft von Javascript in Kombination mit jQuery.

Interessant an der Umsetzung ist der Fakt das keinerlei Pixel berechnet werden, es wird nicht mit Canvas oder Image-Transformationen gearbeitet, sondern einfach ein DIV-Tag clever mit CSS kombiniert. Die Basisideee (die nicht von mir ist) besteht darin die CSS-Property background-position dieses DIV-Tags zu manipulieren. Außerdem wird das quadratische DIV-Tag mittels der CSS-Property border-radius “Rund” gemacht.

Alles was Sie in diesem Demo sehen ist mit 77 Zeilen Javascript erledigt. Dazu kommen noch 20 Zeilen HTML und 60 Zeilen CSS.

$(document).ready(function() {
	// picture URLs of some cuties
	var URLs = [
		'http://farm6.staticflickr.com/5085/5275801576_57718507fd_b.jpg',
		'http://farm8.staticflickr.com/7178/7131405175_45f1b7ddb8_b.jpg',
		'http://farm8.staticflickr.com/7020/6751571539_35353cd22d_b.jpg',
		'http://farm3.staticflickr.com/2560/4189239614_64f4cc0b46_o.jpg',
		'http://farm3.staticflickr.com/2488/3684369721_1f2b864033_o.jpg',
		'http://farm5.staticflickr.com/4105/5022054910_e01eb5e820_o.jpg'
	];

	// render image picker
	$.each(URLs, function (index, url) {
		$('<img src="' + url + '"/>').appendTo('#thumbs');
	});

	// create magnifying lens
	var lens = $('<div class="lens"></div>').appendTo('body');

	// pick image
	$('#thumbs img').click(function(evt) {
		evt.stopPropagation();
		var src = $(evt.currentTarget).attr('src');
		lens.css('background-image', 'URL("' + src + '")');
		$('#picture').hide().attr('src', src).fadeIn(800);
	});

	// initially pick one random image
	$($('#thumbs img')[(Math.random()*URLs.length)|0]).trigger('click');

	$('body').mousemove(function(evt) { // handle lens movement
	   	var x = evt.pageX, y = evt.pageY;
   		var picture = $('#picture');
		var pos = picture.offset();

   		if (x < (pos.left - 30) || x > (pos.left + picture.width() + 30) ||
   	            y < (pos.top - 30) || y > (pos.top + picture.height() + 30)) {
   	   		lens.hide();
   	   	} else {
   	   		var magnifyBy = picture[0].naturalWidth/picture.width();
   	   		var bgPos = (100+(magnifyBy*(200-x))|0)+'px '+(100+(magnifyBy*(100-y))|0)+'px';
	   		lens.css({top: y-100, left: x-100, 'background-position': bgPos});
   	   		lens.show();
   	   	}
	});

	var snapshotRing = [];
	var snapshots = 0;
	var SNAPSHOT_CAPACITY = 7;

	$('body').click(function(evt) { // take snapshot
	  	var pos = lens.offset();

	        // simulate the release of an objective lens
	   	var clone = lens.clone().appendTo('body');
	   	clone.css('background', 'black').animate({opacity:0.6}, 'fast', function() {
			$(this).remove()
		});

		// create a snapshot element
	   	var snap = lens.clone().appendTo('body').addClass('snapshot').css('opacity', 0.2);	  

		// move snapshot in place
		var delta = {
			top: 200 + 180*Math.sin(2*Math.PI*snapshots/SNAPSHOT_CAPACITY) - pos.top,
			left: 950 + 180*Math.cos(2*Math.PI*snapshots/SNAPSHOT_CAPACITY) - pos.left};
		snap.animate({top:'+=' + delta.top, left:'+=' + delta.left, opacity:1}, 500);

		// remove old snapshot from the "ring buffer"
		snapshots++;
		snapshotRing.push(snap);
		if (snapshotRing.length > SNAPSHOT_CAPACITY) {
			 snapshotRing[0].fadeOut(function() {$(this).remove()});
			 snapshotRing.splice(0,1);
		}
	});
});
Posted in Fingerübung | Tagged , , | 1 Comment