Drawing lines with Processing


There are a few general things of note here:

1) I’ve renamed stuff to reflect the fact that we’re dealing with a link map here, not a tree view.

2) Ids have been added to each site/page, so has a links array which contains ids to other pages they’re linking to.

3) We’re only drawing straight lines so far, and they’re not terminating in the middle of the texts, rather the top left corner. That’s something we have to fix later.

4) Still no mouse interaction.

That’s it, lets’ talk about the rest after the listing.

Let’s walk the JavaScript in the demo:

var p = {};

var lmap = {};

lmap.data = [
	{"id": 1, "name": "Site 1", "type": "external", "links": []}, 
	{"id": 2, "name": "Site 2", "type": "internal", "links": [3, 4, 1]},
	{"id": 3, "name": "Site 3", "type": "internal", "links": [1, 2]},
	{"id": 4, "name": "Site 4", "type": "internal", "links": [2]},
	{"id": 5, "name": "Site 5", "type": "internal", "links": [4, 3]}
];

lmap.setup = function(){  
    p.size(800, 800);
    p.strokeWeight(2);
	var arial = p.loadFont("arial.svg");
	p.textFont(arial, 14);
}

function tFill(type){
	if(type == "external"){
		p.fill(150, 50, 50);
		p.stroke(150, 50, 50, 50);
	}else{
		p.fill(50, 50, 150);
		p.stroke(50, 50, 150, 50);
	}
}

function findPage(id){
	var robj = false;
	$.each(lmap.data, function(i, obj){
		if(obj.id == id)
			robj = obj;
	});
	return robj;
}

lmap.draw = function(){
	p.fill(0);
	
	var radius = 350;
	var pi_offset = p.TWO_PI / lmap.data.length;
	var angle = 0;
	var c_x = 400;
	var c_y = 400;
	
	$.each(lmap.data, function(i, obj){
		tFill(obj.type);
			
		var xpos = lmap.data[i].xpos = c_x + radius * p.cos(angle);
		var ypos = lmap.data[i].ypos = c_y + radius * p.sin(angle);
		
		p.text(obj.name, xpos, ypos);
		angle += pi_offset;
	});
	
	$.each(lmap.data, function(i, obj){
		$.each(obj.links, function(i, id){
			var to_obj = findPage(id);
			tFill(to_obj.type);
			p.line(obj.xpos, obj.ypos, to_obj.xpos, to_obj.ypos);
		});
	});
	        
    p.exit();
}

$(document).ready(function(){
	p = Processing("treemap");
	p.setup = lmap.setup;
	p.draw = lmap.draw;
	p.init();
});

The big change is that we now have a stroke weight of 2. We also do two passes, first to render the texts, just like in the prior tutorial. In the first pass we store the x and y coordinates of each text.

In the second pass we use the x and y coordinates we stored in the first pass to draw the lines, we use the same colors as we did with the texts, however we set an alpha value of 50 (half way transparent).

FindPage() is simply a convenience function to get a page by id, so is tFill, in order to set colors (note the last 50 there in the stroke call, that’s the opacity/alpha.


Related Posts

Tags: , , , ,