SlideShare a Scribd company logo
From SVG/D3 to Angular2/React
Oswald Campesato
www.iquarkt.com
ocampesato@yahoo.com
Features of SVG
The SVG <line> Element
The SVG <ellipse> Element
The SVG <rect> Element
The SVG <polygon> Element
The SVG <polyline> Element
The SVG <path> Element
Features of SVG
SVG <linearGradient> Element
SVG <radialGradient> Element
SVG <filter> Element
SVG <pattern> Element
SVG <defs> Element
SVG <text> elements (super/sub)
SVG <use> Element
SVG Fonts and WOFF
Custom Glyphs/Unicode
Colors/Gradients/Filters
(R,G,B) color model
SVG Linear Gradients
SVG Radial Gradients
SVG <pattern> Element
SVG <filter> Element
SVG <feColorMatrix> Filter
Gaussian, emboss, and so forth
SVG Transforms/Animation
The SVG <translate> Transform
The SVG <rotate> Transform
The SVG <scale> Transform
The SVG <skewX> Transform
The SVG <mask> Element
The SVG <clipPath> Element
NB: SMIL is (not?) deprecated in Chrome
SVG and Other Technologies
SVG and CSS
SVG and D3
SVG and jQuery
SVG and AngularJS
SVG and PolymerJS
SVG and ReactJS
The SVG Tiger (240 Path Elements)
Other Aspects of SVG
 SVG elements are inserted in the DOM so you can
track/manage groups of SVG elements
 no blurred/jagged edges when zooming in
 Convenient format for import/export between tools
 Can apply XSL stylesheets to SVG documents
On the other hand:
• Verbose (what do you expect? It’s XML)
• Can be difficult/incomprehensible (SVG tiger)
 Animation code can be cumbersome/tedious
 Consider D3 instead of “pure” SVG
Blog by Patrick Dengler: SVG versus Canvas
Useful Features of SVG (summary)
An XML-based vocabulary for 2D shapes:
 render circles/ellipses/elliptic arcs
 squares/rectangles/parallelograms
 cubic/quadratic Bezier curves
 arbitrary polygons
 linear/radial gradients and filters
 mouse events and animation support (*)
 good for charts/graphs
 works well with CSS3
 (*) consider using D3.js
What is D3?
open source project (2010)
Mike Bostock (principal/creator)
based on JavaScript
a layer of "abstraction" over SVG
also support for HTML5 Canvas
github.com/mbostock/d3
Make sure to visit this website:
https://github.com/mbostock/d3/wiki/Gallery
D3 Functionality
D3 on Mobile Devices
D3 Boilerplate
Method Chaining in D3
The D3 Methods select() and selectAll()
Creating New HTML Elements
The Most Common Idiom in D3 (TMCIID3)
Binding Data to DOM Elements
Generating Text Strings
More Features of D3
Bezier Curves and Text
2D Transforms
Scaling Arrays of Numbers
Tweening in D3
Formatting Numbers
Linear/Radial Gradients
Render PNG Files
D3 and Filters
D3 API Reference
Why/When use D3?
For data visualization
extremely versatile
leverage JavaScript skills
leverage SVG
Create HTML5 Web pages with D3 and:
HTML5 Canvas, CSS3, SVG, jQuery, …
What Can You Do With D3?
All the stuff you can do in SVG
graphics/animation
filters/gradients
mouse/keyboard events
custom charts/graphs
Support for Ajax, JSON, XML, CSV files
How Does D3 Work?
Creates SVG elements via JavaScript
Often involves “method chaining”:
svg.selectAll()
.attr(a, “b”)
.attr(c,”d”)…
attributes: use constants/variables/functions
select-data-enter-append:
"TMCIID3” ("The Most Common Idiom in D3”)
Example: Append <p> with D3
<head>
<script src="d3.min.js"></script>
<script>
d3.select("body")
.append("p")
.text("Hello1 D3");
</script>
<body>
<p>Hello1 D3</p>
</body>
Add SVG Elements: General Approach
#1: create/append an <svg> element to <body>
#2: often define JavaScript array(s) of values
#3: iterate through arrays + create SVG elements:
use constants/variables/anonymous functions
Optional:
#4: add event listener(s)
#5: add animation-related code
Creating a Circle in D3 (1/2)
1) First create an <svg> element:
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height",height);
Creating a Circle in D3 (2/2)
2) Include the following D3 code:
svg.append("circle")
.attr("cx", 10)
.attr("cy", 10)
.attr("r", 100)
.attr("fill", "red")
D3 code generates this SVG element:
<body>
<circle cx="10" cy="10” r="100" fill="red" />
</body>
A Scatter Chart (1/2)
Step #1 define a JS array with data values:
var dataXValues=[10, 50, 20, 80,150,180,220];
Step #2 Create an SVG element:
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
A Scatter Chart (2/2)
Step 3: create and append circles:
var circles = svg.selectAll("circles")
.data(dataXValues)
.enter()
.append("circle")
.attr("cx", function(d, i) {
return (d*5*Math.random());
})
.attr("cy", function(d, i) {
return (d*5*Math.random());
})
.attr("r", radius).style("fill", "red");
Use Arrays of Arrays (or Objects)
var dataXYValues=[[10,30], [50,70], [20,200],
[80,300],[70,50],[180,100],[220,250]];
var generalizedCircles = svg.selectAll("circles")
.data(dataXYValues).enter().append("circle")
.attr("cx", function(d, i) { return d[0]; })
.attr("cy", function(d, i) { return d[1]; })
.attr(”r", function(d, i) { return dataRValues[i];})
.style (”fill", function(d, i) { return dataFValues[i];})
Mouse Handler for ScatterChart
circles.on("mouseover",function() {
d3.select(this) // the “mouseover” circle
.transition()
.duration(duration)
.attr("transform", function() {
var sx = 1+Math.random();
var sy = 1-Math.random();
return "scale("+sx+","+sy+")";
})
})
Examples of Transforms in D3
yourPreviouslyCreatedSVGElement
.attr("transform", "translate(50,100)")
.attr("transform", "rotate(40)")
.attr("transform", "scale(0.5,1.3)")
.attr("transform", "skewX(20)")
Easing Functions (for animation)
Create an SVG element and append this code:
.on("mouseover",function(){
.duration(1000)
.delay(200)
.ease("out-elastic",1,1)
})
At least 10 easing functions available
The SVG Tiger Meets D3
d3.selectAll("path")
.on("mouseover", function(d,i) {
d3.select(this)
.transition()
.duration(1000)
.attr("transform",
"skewX("+40+50*Math.random()+")")
})
2D Bar Charts in D3
Scale horizontal/vertical values
Various label types (numeric/date) for axes
Unicode support
Add mouse events to ‘bar’ elements
What about 3D Bar Charts?
No 3D support in SVG (SVG 2 in 2014?)
Option #1:
Use custom JavaScript to render a cube-like shape
(aka parallelopiped)
Involves 1 rectangle and 2 parallelograms
Use <rect> and <polygon> to render them
Option #2: combine CSS3 3D with SVG
D3 and SVG Filters
Define an SVG <filter> element (in <defs>):
<defs>
…
<filter id="blurFilter1”>
<feGaussianBlur "stdDeviation"=4>
</feGaussianBlur>
</filter>
…
</defs>
How to Define Filters in D3
var defs = svg.append("defs")
defs.append("svg:filter")
.attr("id", "blurFilter1")
.append("svg:feGaussianBlur")
.attr("stdDeviation", 4);
The preceding code is equivalent to this code:
<filter id="blurFilter1”>
<feGaussianBlur "stdDeviation"=4 />
</filter>
Example: SimpleTree1BlurFilter1.html
D3 and SVG Linear Gradients
Insert this code in an SVG <defs> element:
<linearGradient id="GradientL"
gradientUnits="userSpaceOnUse"
cx="100" cy="50" r="160"
fx="100" fy="50">
<stop offset="0%" stop-color="red"/>
<stop offset="33%" stop-color="blue"/>
<stop offset="67%" stop-color="red"/>
<stop offset="100%" stop-color="blue"/>
</linearGradient>
D3 Linear Gradients
var gradientL = defsElement
.append("svg:linearGradient")
.attr("id", "GradientL")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "100%")
.attr("gradientUnits",
"userSpaceOnUs”)
Append-stop-colors…
D3 and the SVG <pattern> Element
Insert in the SVG <defs> element:
<pattern id="checkerPattern"
width="40" height="40"
patternUnits="userSpaceOnUse”>
<rect fill="url(#gradientDefinition1)"
x="0" y="0" width="40" height="40"/>
</pattern>
D3 code for an SVG pattern: exercise
Ex: MultiPartialBlueSphereCB5AnimMouseMove1
D3 APIs/Extensions/Plugins
Choropleth
Maps (stereographic projection/others)
Force diagrams
Extensions/plugins:
RickShaw
CS
Extensions:
Cubed
D3 and CSV Files
Read data from a CSV file (1,000 rows)
Each row represents a line segment
Add a mouseover event listener
Append line coordinates to a second array
when users ‘mouse over’ that segment
Works fine for up to 4,000 rows
What about Large Datasets?
Superconductor.js:
DSL/JS/Web Workers
Uses a <canvas> element
“browser in a browser”
Smoothly handles 100K data points
• Druid (Metamarkets)
• Weave/Yarn (Apache): layer over Hadoop
• Kafka, Storm, and D3 (more recent)
D3 and CSS3 2D/3D Transforms
CSS3 2D transforms:
rotate, scale, skew, translate, matrix, and
perspective
• CSS3 3D transforms:
Similar to 2D versions (but no ‘skew’)
Also three axis-specific methods:
rotateX, rotateY, rotateZ
Working with Angular 2
Component-based framework (all JavaScript)
One-way data binding (default)
New syntax: [item], (click), [(update)]
No ng-app, ng-controller, ng-click, …
Create your own custom components
What are Transpilers?
 They convert code from one language to another
 Babel (formerly 6to5):
+converts ES6 (some ES7) to ECMA5
+ appears to be the de facto standard
 Traceur (Google):
+ converts ES6 to ECMA5
+ used by Angular 2
TypeScript (MicroSoft): http://www.TypeScriptlang.org
What about ES6?
Arrow functions and let keyword
Block scopes
Classes and inheritance
Default parameters
Destructured assignment
Generators, Iterators, Maps, and Sets
Promises and Rest parameters
Spread operator
Template Literals
What is TypeScript?
 A superset of JavaScript (ES6): 10/01/2012
 A compiled language (tsc compiler)
 strong typing and also type inferencing
 Type checking during compile time
 “minimal” extra compile time overhead
 “.ts” files are transpiled into “.js” files (via tsc)
 “lib.d.ts” contains TypeScript definitions
 TypeScript type definitions (update via “nuget”):
https://github.com/borisyankov/DefinitelyTyped
TypeScript Variables
 var isDone: boolean = false;
 var height: number = 6;
 var name: string = "dave";
 var myList:number[] = [1, 2, 3]; // option #1
 var myList:Array<number> = [1, 2, 3]; // option #2
 var changeMe: any = 4;
 changeMe = ”I’m a string now";
 var myList:any[] = [1, true, ”pizza"];
TypeScript Functions
 void return type:
function myLogger(msg?:string): void {
console.log("My custom logger: “+msg);
}
 Generics:
function identity<T>(arg: T): T {
return arg;
}
// output has 'string' type (explicit/inferred):
var output = identity<string>("Dave");
var output = identity("Dave");
Angular 2 + TypeScript Example
import {Component, bootstrap} from 'angular2/core';
@Component({
selector: 'my-app’,
template: '<h1>Hello {{ name }}</h1>'
})
class MyAppComponent { // component controller
constructor() {
this.name = 'World!';
}
}
bootstrap(MyAppComponent);
Angular 2 and Event Objects
<button (click)="clicked($event)"></button>
@Component(...)
class MyComponent {
clicked(event) {
event.preventDefault();
// do stuff here
}
}
bootstrap(MyComponent);
Angular 2 Syntax
 [attribute] syntax:
<input [value]="name”>
 (method) syntax:
<input #myname (keyup)=”vm.myCtrlMethod()">
 ^ symbol handles bubble up events:
<div (^click)=”handleClick()">
<div></div>
</div>
 [(method)] syntax for two-way binding:
<input [(ng-model)]=”vm.foo”>
<p>Hello {{vm.foo}}</p>
“Hello World” in Angular 2 (1/3)
 <!DOCTYPE html>
 <html>
 <head>
 <script src="https://code.angularjs.org/2.0.0-beta.0/angular2-
polyfills.js">
 </script>
 <script
src="https://code.angularjs.org/tools/system.js"></script>
 <script
src="https://code.angularjs.org/tools/typescript.js"></script>
 <script src="https://code.angularjs.org/2.0.0-
beta.0/Rx.js"></script>
 <script src="https://code.angularjs.org/2.0.0-
beta.0/angular2.dev.js"></script>
“Hello World” in Angular 2 (2/3)
 <script>
 System.config({
 transpiler: 'typescript',
 typescriptOptions: { emitDecoratorMetadata: true },
 packages: {'app': {defaultExtension: 'ts'}}
 });
 System.import('app/main')
 .then(null, console.error.bind(console));
 </script>
 </head>
 <body>
 <my-app>Loading...</my-app>
 </body>
 </html>
“Hello World” in Angular 2 (3/3)
 import {bootstrap} from 'angular2/platform/browser';
 import {Component} from 'angular2/core';
 @Component({
 selector: 'my-app',
 template: `<div>Hello from Angular 2</div>`
 })
 class MyApp {}
 bootstrap(MyApp);
 NB: this is the contents of app/main.ts
SVG in Angular 2 (main.ts)
 import {bootstrap} from 'angular2/platform/browser';
 import {Component} from 'angular2/core';
 import {MyEllipse} from './my-svg';
 @Component({
 selector: 'my-app',
 directives: [MyEllipse],
 template: `<div><my-svg></my-svg></div>`
 })
 class MyApp {}
 bootstrap(MyApp);
SVG in Angular 2 (my-svg.ts)
 import {Component} from 'angular2/core';
 @Component({
 selector: 'my-svg',
 template: `<svg width="500" height="300">
 <ellipse cx="100" cy="100"
 rx="50" ry="30” fill="red"/>
 </svg>
 `
 })
 export class MyEllipse{}
D3 Code for a Cube (1/2)
 // ADD YOUR CUSTOM D3 CODE HERE
 var width = 300, height = 300, fillColors = ["red", "yellow", "blue"];
 var points1 = "50,50 200,50 240,30 90,30";
 var points2 = "200,50 200,200 240,180 240,30";
 // “outer” SVG element (contains the cube):
 var svg = d3.select(el)
 .append("svg")
 .attr("width", width)
 .attr("height", height);
 // top face (parallelogram):
 var polygon = svg.append("polygon")
 .attr("points", points1)
 .attr("fill", fillColors )
 .attr("stroke", "blue")
 .attr("stroke-width", 1);
D3 Code for a Cube (2/2)
 // front face (rectangle)
 svg.append("rect")
 .attr("x", 50)
 .attr("y", 50)
 .attr("width", 150)
 .attr("height", 150)
 .attr("fill", fillColors[0]);
 // right face (parallelogram)
 var polygon = svg.append("polygon")
 .attr("points", points2)
 .attr("fill", fillColors[2])
 .attr("stroke", "blue")
 .attr("stroke-width", 1);
What about ReactJS?
Provides “V” in MVC
One-way data binding
JSX (optional)
Hierarchical set of components
“React” = top-level namespace
Maintains a “virtual DOM”
Only updates the “delta”
Hence it’s very efficient
“Hello World” in ReactJS (1/2)
 <!DOCTYPE html>
 <html>
 <head>

 <script src="https://fb.me/react-0.14.3.js">
 </script>
 <script src="https://fb.me/react-dom-0.14.3.js">
 </script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-
core/5.8.23/browser.min.js">
 </script>
 </head>
 <body>
 <div id="hello"></div>
“Hello World” in ReactJS (2/2)
 <script type="text/babel">
 class Hello extends React.Component {
 constructor () {
 super();
 }
 render() {
 return <div>Hello World</div>
 }
 }
ReactDOM.render(<Hello/>,
document.getElementById('hello'));
 </script>
 </body></html>
SVG in ReactJS (1/2)
 <!DOCTYPE html>
 <html>
 <head>

 <script src="https://fb.me/react-0.14.3.js">
 </script>
 <script src="https://fb.me/react-dom-0.14.3.js">
 </script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-
core/5.8.23/browser.min.js">
 </script>
 </head>
 <body>
 <div id=”mysvg"></div>
SVG in ReactJS (2/2)
 <script type="text/babel">
 class MySVG extends React.Component {
 constructor () {
 super();
 }
 render() {
 return (
 <svg width="600" height="150">
 <rect width="160" height="80" fill="red"/>
 </svg>
 );
 }
 }
ReactDOM.render(<MySVG/>,
document.getElementById(’mysvg'));
 </script>
 </body></html>
What Should I Learn???
 Main features of ES6 and TypeScript 1.5+
 “basic” Angular 1.5+ and 2 (best practices)
 Practice converting code from ANG 1.x to 2
 Select an IDE:
+WebStorm 10: free 30-day trial ($49/year)
+Visual Studio Code (free)
+ Atom (free) with atom-TypeScript extension
 Command Line Tools:
+ npm, npmjs, gulp, grunt (older), broccoli,
+ webpack, browserify (older), jspm+systemjs
https://github.com/addyosmani/es6-tools
Github + Graphics Samples
 https://github.com/ocampesato/reactjs-graphics
 https://github.com/ocampesato/angular-graphics
 https://github.com/ocampesato/web-animations
 https://github.com/ocampesato/polymer-svg-css3
Recent/Upcoming Books and Training
1) HTML5 Canvas and CSS3 Graphics (2013)
2) jQuery, CSS3, and HTML5 for Mobile (2013)
3) HTML5 Pocket Primer (2013)
4) jQuery Pocket Primer (2013)
5) HTML5 Mobile Pocket Primer (2014)
6) D3 Pocket Primer (2015)
7) Python Pocket Primer (2015)
8) SVG Pocket Primer (2016)
9) CSS3 Pocket Primer (2016)
10) Angular Pocket Primer (2016)

More Related Content

SVGD3Angular2React

  • 1. From SVG/D3 to Angular2/React Oswald Campesato www.iquarkt.com ocampesato@yahoo.com
  • 2. Features of SVG The SVG <line> Element The SVG <ellipse> Element The SVG <rect> Element The SVG <polygon> Element The SVG <polyline> Element The SVG <path> Element
  • 3. Features of SVG SVG <linearGradient> Element SVG <radialGradient> Element SVG <filter> Element SVG <pattern> Element SVG <defs> Element SVG <text> elements (super/sub) SVG <use> Element SVG Fonts and WOFF Custom Glyphs/Unicode
  • 4. Colors/Gradients/Filters (R,G,B) color model SVG Linear Gradients SVG Radial Gradients SVG <pattern> Element SVG <filter> Element SVG <feColorMatrix> Filter Gaussian, emboss, and so forth
  • 5. SVG Transforms/Animation The SVG <translate> Transform The SVG <rotate> Transform The SVG <scale> Transform The SVG <skewX> Transform The SVG <mask> Element The SVG <clipPath> Element NB: SMIL is (not?) deprecated in Chrome
  • 6. SVG and Other Technologies SVG and CSS SVG and D3 SVG and jQuery SVG and AngularJS SVG and PolymerJS SVG and ReactJS
  • 7. The SVG Tiger (240 Path Elements)
  • 8. Other Aspects of SVG  SVG elements are inserted in the DOM so you can track/manage groups of SVG elements  no blurred/jagged edges when zooming in  Convenient format for import/export between tools  Can apply XSL stylesheets to SVG documents On the other hand: • Verbose (what do you expect? It’s XML) • Can be difficult/incomprehensible (SVG tiger)  Animation code can be cumbersome/tedious  Consider D3 instead of “pure” SVG Blog by Patrick Dengler: SVG versus Canvas
  • 9. Useful Features of SVG (summary) An XML-based vocabulary for 2D shapes:  render circles/ellipses/elliptic arcs  squares/rectangles/parallelograms  cubic/quadratic Bezier curves  arbitrary polygons  linear/radial gradients and filters  mouse events and animation support (*)  good for charts/graphs  works well with CSS3  (*) consider using D3.js
  • 10. What is D3? open source project (2010) Mike Bostock (principal/creator) based on JavaScript a layer of "abstraction" over SVG also support for HTML5 Canvas github.com/mbostock/d3 Make sure to visit this website: https://github.com/mbostock/d3/wiki/Gallery
  • 11. D3 Functionality D3 on Mobile Devices D3 Boilerplate Method Chaining in D3 The D3 Methods select() and selectAll() Creating New HTML Elements The Most Common Idiom in D3 (TMCIID3) Binding Data to DOM Elements Generating Text Strings
  • 12. More Features of D3 Bezier Curves and Text 2D Transforms Scaling Arrays of Numbers Tweening in D3 Formatting Numbers Linear/Radial Gradients Render PNG Files D3 and Filters D3 API Reference
  • 13. Why/When use D3? For data visualization extremely versatile leverage JavaScript skills leverage SVG Create HTML5 Web pages with D3 and: HTML5 Canvas, CSS3, SVG, jQuery, …
  • 14. What Can You Do With D3? All the stuff you can do in SVG graphics/animation filters/gradients mouse/keyboard events custom charts/graphs Support for Ajax, JSON, XML, CSV files
  • 15. How Does D3 Work? Creates SVG elements via JavaScript Often involves “method chaining”: svg.selectAll() .attr(a, “b”) .attr(c,”d”)… attributes: use constants/variables/functions select-data-enter-append: "TMCIID3” ("The Most Common Idiom in D3”)
  • 16. Example: Append <p> with D3 <head> <script src="d3.min.js"></script> <script> d3.select("body") .append("p") .text("Hello1 D3"); </script> <body> <p>Hello1 D3</p> </body>
  • 17. Add SVG Elements: General Approach #1: create/append an <svg> element to <body> #2: often define JavaScript array(s) of values #3: iterate through arrays + create SVG elements: use constants/variables/anonymous functions Optional: #4: add event listener(s) #5: add animation-related code
  • 18. Creating a Circle in D3 (1/2) 1) First create an <svg> element: var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height",height);
  • 19. Creating a Circle in D3 (2/2) 2) Include the following D3 code: svg.append("circle") .attr("cx", 10) .attr("cy", 10) .attr("r", 100) .attr("fill", "red") D3 code generates this SVG element: <body> <circle cx="10" cy="10” r="100" fill="red" /> </body>
  • 20. A Scatter Chart (1/2) Step #1 define a JS array with data values: var dataXValues=[10, 50, 20, 80,150,180,220]; Step #2 Create an SVG element: var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height);
  • 21. A Scatter Chart (2/2) Step 3: create and append circles: var circles = svg.selectAll("circles") .data(dataXValues) .enter() .append("circle") .attr("cx", function(d, i) { return (d*5*Math.random()); }) .attr("cy", function(d, i) { return (d*5*Math.random()); }) .attr("r", radius).style("fill", "red");
  • 22. Use Arrays of Arrays (or Objects) var dataXYValues=[[10,30], [50,70], [20,200], [80,300],[70,50],[180,100],[220,250]]; var generalizedCircles = svg.selectAll("circles") .data(dataXYValues).enter().append("circle") .attr("cx", function(d, i) { return d[0]; }) .attr("cy", function(d, i) { return d[1]; }) .attr(”r", function(d, i) { return dataRValues[i];}) .style (”fill", function(d, i) { return dataFValues[i];})
  • 23. Mouse Handler for ScatterChart circles.on("mouseover",function() { d3.select(this) // the “mouseover” circle .transition() .duration(duration) .attr("transform", function() { var sx = 1+Math.random(); var sy = 1-Math.random(); return "scale("+sx+","+sy+")"; }) })
  • 24. Examples of Transforms in D3 yourPreviouslyCreatedSVGElement .attr("transform", "translate(50,100)") .attr("transform", "rotate(40)") .attr("transform", "scale(0.5,1.3)") .attr("transform", "skewX(20)")
  • 25. Easing Functions (for animation) Create an SVG element and append this code: .on("mouseover",function(){ .duration(1000) .delay(200) .ease("out-elastic",1,1) }) At least 10 easing functions available
  • 26. The SVG Tiger Meets D3 d3.selectAll("path") .on("mouseover", function(d,i) { d3.select(this) .transition() .duration(1000) .attr("transform", "skewX("+40+50*Math.random()+")") })
  • 27. 2D Bar Charts in D3 Scale horizontal/vertical values Various label types (numeric/date) for axes Unicode support Add mouse events to ‘bar’ elements
  • 28. What about 3D Bar Charts? No 3D support in SVG (SVG 2 in 2014?) Option #1: Use custom JavaScript to render a cube-like shape (aka parallelopiped) Involves 1 rectangle and 2 parallelograms Use <rect> and <polygon> to render them Option #2: combine CSS3 3D with SVG
  • 29. D3 and SVG Filters Define an SVG <filter> element (in <defs>): <defs> … <filter id="blurFilter1”> <feGaussianBlur "stdDeviation"=4> </feGaussianBlur> </filter> … </defs>
  • 30. How to Define Filters in D3 var defs = svg.append("defs") defs.append("svg:filter") .attr("id", "blurFilter1") .append("svg:feGaussianBlur") .attr("stdDeviation", 4); The preceding code is equivalent to this code: <filter id="blurFilter1”> <feGaussianBlur "stdDeviation"=4 /> </filter> Example: SimpleTree1BlurFilter1.html
  • 31. D3 and SVG Linear Gradients Insert this code in an SVG <defs> element: <linearGradient id="GradientL" gradientUnits="userSpaceOnUse" cx="100" cy="50" r="160" fx="100" fy="50"> <stop offset="0%" stop-color="red"/> <stop offset="33%" stop-color="blue"/> <stop offset="67%" stop-color="red"/> <stop offset="100%" stop-color="blue"/> </linearGradient>
  • 32. D3 Linear Gradients var gradientL = defsElement .append("svg:linearGradient") .attr("id", "GradientL") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "100%") .attr("gradientUnits", "userSpaceOnUs”) Append-stop-colors…
  • 33. D3 and the SVG <pattern> Element Insert in the SVG <defs> element: <pattern id="checkerPattern" width="40" height="40" patternUnits="userSpaceOnUse”> <rect fill="url(#gradientDefinition1)" x="0" y="0" width="40" height="40"/> </pattern> D3 code for an SVG pattern: exercise Ex: MultiPartialBlueSphereCB5AnimMouseMove1
  • 34. D3 APIs/Extensions/Plugins Choropleth Maps (stereographic projection/others) Force diagrams Extensions/plugins: RickShaw CS Extensions: Cubed
  • 35. D3 and CSV Files Read data from a CSV file (1,000 rows) Each row represents a line segment Add a mouseover event listener Append line coordinates to a second array when users ‘mouse over’ that segment Works fine for up to 4,000 rows
  • 36. What about Large Datasets? Superconductor.js: DSL/JS/Web Workers Uses a <canvas> element “browser in a browser” Smoothly handles 100K data points • Druid (Metamarkets) • Weave/Yarn (Apache): layer over Hadoop • Kafka, Storm, and D3 (more recent)
  • 37. D3 and CSS3 2D/3D Transforms CSS3 2D transforms: rotate, scale, skew, translate, matrix, and perspective • CSS3 3D transforms: Similar to 2D versions (but no ‘skew’) Also three axis-specific methods: rotateX, rotateY, rotateZ
  • 38. Working with Angular 2 Component-based framework (all JavaScript) One-way data binding (default) New syntax: [item], (click), [(update)] No ng-app, ng-controller, ng-click, … Create your own custom components
  • 39. What are Transpilers?  They convert code from one language to another  Babel (formerly 6to5): +converts ES6 (some ES7) to ECMA5 + appears to be the de facto standard  Traceur (Google): + converts ES6 to ECMA5 + used by Angular 2 TypeScript (MicroSoft): http://www.TypeScriptlang.org
  • 40. What about ES6? Arrow functions and let keyword Block scopes Classes and inheritance Default parameters Destructured assignment Generators, Iterators, Maps, and Sets Promises and Rest parameters Spread operator Template Literals
  • 41. What is TypeScript?  A superset of JavaScript (ES6): 10/01/2012  A compiled language (tsc compiler)  strong typing and also type inferencing  Type checking during compile time  “minimal” extra compile time overhead  “.ts” files are transpiled into “.js” files (via tsc)  “lib.d.ts” contains TypeScript definitions  TypeScript type definitions (update via “nuget”): https://github.com/borisyankov/DefinitelyTyped
  • 42. TypeScript Variables  var isDone: boolean = false;  var height: number = 6;  var name: string = "dave";  var myList:number[] = [1, 2, 3]; // option #1  var myList:Array<number> = [1, 2, 3]; // option #2  var changeMe: any = 4;  changeMe = ”I’m a string now";  var myList:any[] = [1, true, ”pizza"];
  • 43. TypeScript Functions  void return type: function myLogger(msg?:string): void { console.log("My custom logger: “+msg); }  Generics: function identity<T>(arg: T): T { return arg; } // output has 'string' type (explicit/inferred): var output = identity<string>("Dave"); var output = identity("Dave");
  • 44. Angular 2 + TypeScript Example import {Component, bootstrap} from 'angular2/core'; @Component({ selector: 'my-app’, template: '<h1>Hello {{ name }}</h1>' }) class MyAppComponent { // component controller constructor() { this.name = 'World!'; } } bootstrap(MyAppComponent);
  • 45. Angular 2 and Event Objects <button (click)="clicked($event)"></button> @Component(...) class MyComponent { clicked(event) { event.preventDefault(); // do stuff here } } bootstrap(MyComponent);
  • 46. Angular 2 Syntax  [attribute] syntax: <input [value]="name”>  (method) syntax: <input #myname (keyup)=”vm.myCtrlMethod()">  ^ symbol handles bubble up events: <div (^click)=”handleClick()"> <div></div> </div>  [(method)] syntax for two-way binding: <input [(ng-model)]=”vm.foo”> <p>Hello {{vm.foo}}</p>
  • 47. “Hello World” in Angular 2 (1/3)  <!DOCTYPE html>  <html>  <head>  <script src="https://code.angularjs.org/2.0.0-beta.0/angular2- polyfills.js">  </script>  <script src="https://code.angularjs.org/tools/system.js"></script>  <script src="https://code.angularjs.org/tools/typescript.js"></script>  <script src="https://code.angularjs.org/2.0.0- beta.0/Rx.js"></script>  <script src="https://code.angularjs.org/2.0.0- beta.0/angular2.dev.js"></script>
  • 48. “Hello World” in Angular 2 (2/3)  <script>  System.config({  transpiler: 'typescript',  typescriptOptions: { emitDecoratorMetadata: true },  packages: {'app': {defaultExtension: 'ts'}}  });  System.import('app/main')  .then(null, console.error.bind(console));  </script>  </head>  <body>  <my-app>Loading...</my-app>  </body>  </html>
  • 49. “Hello World” in Angular 2 (3/3)  import {bootstrap} from 'angular2/platform/browser';  import {Component} from 'angular2/core';  @Component({  selector: 'my-app',  template: `<div>Hello from Angular 2</div>`  })  class MyApp {}  bootstrap(MyApp);  NB: this is the contents of app/main.ts
  • 50. SVG in Angular 2 (main.ts)  import {bootstrap} from 'angular2/platform/browser';  import {Component} from 'angular2/core';  import {MyEllipse} from './my-svg';  @Component({  selector: 'my-app',  directives: [MyEllipse],  template: `<div><my-svg></my-svg></div>`  })  class MyApp {}  bootstrap(MyApp);
  • 51. SVG in Angular 2 (my-svg.ts)  import {Component} from 'angular2/core';  @Component({  selector: 'my-svg',  template: `<svg width="500" height="300">  <ellipse cx="100" cy="100"  rx="50" ry="30” fill="red"/>  </svg>  `  })  export class MyEllipse{}
  • 52. D3 Code for a Cube (1/2)  // ADD YOUR CUSTOM D3 CODE HERE  var width = 300, height = 300, fillColors = ["red", "yellow", "blue"];  var points1 = "50,50 200,50 240,30 90,30";  var points2 = "200,50 200,200 240,180 240,30";  // “outer” SVG element (contains the cube):  var svg = d3.select(el)  .append("svg")  .attr("width", width)  .attr("height", height);  // top face (parallelogram):  var polygon = svg.append("polygon")  .attr("points", points1)  .attr("fill", fillColors )  .attr("stroke", "blue")  .attr("stroke-width", 1);
  • 53. D3 Code for a Cube (2/2)  // front face (rectangle)  svg.append("rect")  .attr("x", 50)  .attr("y", 50)  .attr("width", 150)  .attr("height", 150)  .attr("fill", fillColors[0]);  // right face (parallelogram)  var polygon = svg.append("polygon")  .attr("points", points2)  .attr("fill", fillColors[2])  .attr("stroke", "blue")  .attr("stroke-width", 1);
  • 54. What about ReactJS? Provides “V” in MVC One-way data binding JSX (optional) Hierarchical set of components “React” = top-level namespace Maintains a “virtual DOM” Only updates the “delta” Hence it’s very efficient
  • 55. “Hello World” in ReactJS (1/2)  <!DOCTYPE html>  <html>  <head>   <script src="https://fb.me/react-0.14.3.js">  </script>  <script src="https://fb.me/react-dom-0.14.3.js">  </script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel- core/5.8.23/browser.min.js">  </script>  </head>  <body>  <div id="hello"></div>
  • 56. “Hello World” in ReactJS (2/2)  <script type="text/babel">  class Hello extends React.Component {  constructor () {  super();  }  render() {  return <div>Hello World</div>  }  } ReactDOM.render(<Hello/>, document.getElementById('hello'));  </script>  </body></html>
  • 57. SVG in ReactJS (1/2)  <!DOCTYPE html>  <html>  <head>   <script src="https://fb.me/react-0.14.3.js">  </script>  <script src="https://fb.me/react-dom-0.14.3.js">  </script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel- core/5.8.23/browser.min.js">  </script>  </head>  <body>  <div id=”mysvg"></div>
  • 58. SVG in ReactJS (2/2)  <script type="text/babel">  class MySVG extends React.Component {  constructor () {  super();  }  render() {  return (  <svg width="600" height="150">  <rect width="160" height="80" fill="red"/>  </svg>  );  }  } ReactDOM.render(<MySVG/>, document.getElementById(’mysvg'));  </script>  </body></html>
  • 59. What Should I Learn???  Main features of ES6 and TypeScript 1.5+  “basic” Angular 1.5+ and 2 (best practices)  Practice converting code from ANG 1.x to 2  Select an IDE: +WebStorm 10: free 30-day trial ($49/year) +Visual Studio Code (free) + Atom (free) with atom-TypeScript extension  Command Line Tools: + npm, npmjs, gulp, grunt (older), broccoli, + webpack, browserify (older), jspm+systemjs https://github.com/addyosmani/es6-tools
  • 60. Github + Graphics Samples  https://github.com/ocampesato/reactjs-graphics  https://github.com/ocampesato/angular-graphics  https://github.com/ocampesato/web-animations  https://github.com/ocampesato/polymer-svg-css3
  • 61. Recent/Upcoming Books and Training 1) HTML5 Canvas and CSS3 Graphics (2013) 2) jQuery, CSS3, and HTML5 for Mobile (2013) 3) HTML5 Pocket Primer (2013) 4) jQuery Pocket Primer (2013) 5) HTML5 Mobile Pocket Primer (2014) 6) D3 Pocket Primer (2015) 7) Python Pocket Primer (2015) 8) SVG Pocket Primer (2016) 9) CSS3 Pocket Primer (2016) 10) Angular Pocket Primer (2016)