Introduction to Web Programming for Visualization 陈思明 北京大学可视化与可视分析实验室 2016.10.19
Visualization
WWW Stuff HTML CSS JavaScript Product Manager Art Designer Programmer Image Source: Pixel4kids.net
HTML Structure Elements <!DOCTYPE html> <html> <head> <title>This is a title</title> <link href="css/index.css" type="text/css" rel="stylesheet" /> </head> <body> <p>Hello world!</p> </body> </html> HTML : HyperText Markup Language the standard markup language used to create web pages. Structure Header Body Embedded assets Elements <div>, <p>, <input>, <span>, etc.
HTML : HyperText Markup Language HTML tags (www.w3schools.com)
HTML Tag Examples
HTML Tag Examples 2 Tables Tr (Row) th/td (Head / Column)
DOM Tree Property Method Event class, text find, insert onclick, onload
CSS CSS : Cascading Style Sheet is a style sheet language used for describing the look and formatting of a document written in a markup language. Inline CSS External CSS
CSS CSS Selector : allow you to select and manipulate HTML element(s). The element Selector The id Selector keyword “id=…” on html tag The class Selector keyword “class=…” on html tag
JavaScript Why JavaScript? : JavaScript is one of 3 languages all web developers MUST learn: HTML to define the content of web pages CSS to specify the layout of web pages JavaScript to program the behavior of web pages Example Scenario Web Engine (Server Side) Web Page (Client Side) request response The request format should be verified on the client side thus verification process will not burden the web server
JavaScript In-line Script External Script http://www.w3schools.com/jsref/default.asp
JavaScript <html> <body> <script type=“text/javascript”> document.write(“<h1>这是标题</h1>”); document.write(“<p>这是段落。</p>”); document.write(“<p>这是另一个段落。</p>”); </script> </body> </html>
JSON More compact storage than XML JavaScript compatible More restrict Key must be double quoted {“key1”:”value1”,”key2”:”value2”}
Reference http://www.w3schools.com http://jquery.com http://www.json.org http://d3js.org
Bootstrap Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web.
Hands-on Build up a website in 5 minutes http://www.bootcss.com/p/layoutit/
D3.js
提纲 Data Driven Documents – D3 D3 Concept D3 Important Features D3 Hands-on
Trend of Visualization Programming Tools Framework Platform Url OpenGL with glut C/C++ http://nehe.gamedev.net/tutorial/lessons_01__05/22004/ OpenFramework http://www.openframeworks.cc/ Java2D with Swing Java http://download.oracle.com/javase/tutorial/2d/index.html Prefuse http://prefuse.org Processing Processing (based on Java) http://processing.org ProtoVis JavaScript http://protovis.org Our recommendations in 2011 But now We recommend Web Programming and D3js Library
Why Web Programing? Users – Everyone can touch it Flexibility – JS code is far less than C++ Library and sharing – Don’t need to build wheels for the cars But Please have graphical programming basic in mind High performance visualization, please turn right for C++
D3.js http://d3js.org One sentence illustration -- Binding data to HTML elements
SVG <svg> <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" /> </svg>
Learning from the ‘Three Little Circle’ – Step 1: Relationship between SVG and D3 http://bost.ocks.org/mike/circles/
Learning from the ‘Three Little Circle’ – Step 2: Selection http://bost.ocks.org/mike/circles/
Learning from the ‘Three Little Circle’ – Step 3: Binding Data http://bost.ocks.org/mike/circles/
D3 Core: Enter – Update - Exit
D3 Core: Enter – Update – Exit Take-home code First to ‘enter’ – when new data coming Remember to ‘update’ – when existing data change values Don’t forget to ‘exit’ – remove what we don’t want
6 Steps to write a visualization
Deconstruct the visualization into primitives X-axis Y-axis X, Y mapping Color encoding Labeling Any interactions
Step 1: Loading the data Loading Data Preprocessing related attributes d3.tsv("data.tsv", function(error, data) { if (error) throw error; data.forEach(function(d) { d.sepalLength = +d.sepalLength; d.sepalWidth = +d.sepalWidth; });
Step 2: Mapping the data Mapping the data Defining the boundary Defining the ‘d3.scale’ Choosing the mapping mechanism – linear, log, etc. Setting the ‘domain’ and ‘range’ var margin = {top: 20, right: 20, bottom: 30, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var x = d3.scale.linear() .range([0, width]); var y = d3.scale.linear() .range([height, 0]); x.domain(d3.extent(data, function(d) { return d.sepalWidth; })).nice(); y.domain(d3.extent(data, function(d) { return d.sepalLength; })).nice();
Step 3: Preparing for drawing var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var xAxis = d3.svg.axis() .scale(x) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left"); SVG is the main canvas for drawing X-axis and Y-axis is mapping with the x and y scale
Step 4: Drawing the primitives Drawing the xAxis Drawing the labels Drawing the yAxis and lables svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) .append("text") .attr("class", "label") .attr("x", width) .attr("y", -6) .style("text-anchor", "end") .text("Sepal Width (cm)"); .attr("class", "y axis") .call(yAxis) .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .text("Sepal Length (cm)")
Step 5: Drawing the Dot Main parts of the drawing Data binding Data entering Data updating svg.selectAll(".dot") .data(data) .enter().append("circle") .attr("class", "dot") .attr("r", 3.5) .attr("cx", function(d) { return x(d.sepalWidth); }) .attr("cy", function(d) { return y(d.sepalLength); }) .style("fill", function(d) { return color(d.species); });
Step 6: Drawing the Legends Labels are the data of categories, in this data is 3 categories Adding the rect and text Setting the contents var legend = svg.selectAll(".legend") .data(color.domain()) .enter().append("g") .attr("class", "legend") .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; }); legend.append("rect") .attr("x", width - 18) .attr("width", 18) .attr("height", 18) .style("fill", color); legend.append("text") .attr("x", width - 24) .attr("y", 9) .attr("dy", ".35em") .style("text-anchor", "end") .text(function(d) { return d; });
JavaScript Closure var counter = 0; function add() { counter += 1; } var add = (function () { var counter = 0; return function () {return counter += 1;} })(); add();
JavaScript var f=function(){return this.a} var a=12 The invocation context var f=function(){return this.a} var a=12 f() // this=window, 12 var o={a:23, f:f} o.f() // this=o, 23 var p={a:34, f:f.bind(o)} p.f() // this=o, 23 o.f.call(p) // this=p, 34 p.f.call(p) // this=o, 23
JavaScript $( "#button" ).on( "click", function( event ) { Callback Single thread Message polling and callback registration $( "#button" ).on( "click", function( event ) { hiddenBox.show(); }); $.ajax({url: "test.html”}).done(function() { $( this ).addClass( "done" );
Graphics Canvas SVG WebGL Runtime generation Complex and high performance SVG Vector graphics XML format
Canvas <canvas id="canvas" width="200" height="100"></canvas> var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); context.beginPath(); context.moveTo(100, 100); context.lineTo(100, 200); context.strokeStyle = "black"; context.stroke(); context.fillStyle = "#FF0000"; context.fillRect(0,0,150,75);
Networking $.ajax({url: ”test", success: function(result){ $("#div1").html(result); }}); $.get(”test", function(data, status){ alert("Data: " + data + "\nStatus: " + status); }); $.ajax({ method: "POST", url: "some.php", data: { name: "John", location: "Boston" } }).done(function( msg ) { alert( "Data Saved: " + msg );});
SVG <svg> <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" /> </svg>