Post on 18-Feb-2017
SVG, CSS3, and D3 for Beginners
Oswald Campesato
Consultant/Training: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 Angular 2 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” SVGBlog by Patrick Dengler: SVG versus Canvas
Ellipses and Rectangles (EllipseRect.svg)
<?xml version="1.0" encoding="iso-8859-1"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20001102//EN" "http://www.w3.org/TR/2000/CR-SVG-20001102/DTD/svg-20001102.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%"><g> <ellipse cx=“100” cy=“100” rx=“80” ry=“30” fill=“blue”/> <rect x=“200” y=“100” width=“80” height=“50” fill=“red”/> </g></svg>
Exercise Set One
1) Render an ellipse that is directly below the given ellipse
2) Render an ellipse that is perpendicular to the given ellipse
3) Repeat #1 and #2 for the rectangle
If you have extra time:4) Create a 2x2 rectangle checkerboard pattern
Rendering Polygons <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20001102//EN" "http://www.w3.org/TR/2000/CR-SVG-20001102/DTD/svg-20001102.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%"> <g> <polygon points="250,20 200,80 300,350 z" fill="blue" stroke="red" stroke-width="4"/>
<polygon points="300,100 100,80 50,50 100,250 z" fill="yellow" stroke="red" stroke-width="4"/> </g> </svg>
Rendering Cubes (basic code) <!-- top face (counter clockwise) --> <polygon fill="red" points="50,50 200,50 240,30 90,30"/>
<!-- front face --> <rect width="150" height="150" x="50" y="50" fill="blue"/>
<!-- right face (counter clockwise) --> <polygon fill="yellow" points="200,50 200,200 240,180 240,30"/>
Exercise Set Two
1) Create a triangle with <polygon>
2) Create a “diamond” shape with polygons
If you have extra time:3) Create a regular octagon with a <polygon> element
4) Create a simple “star” shape with <polygon>
Simple Linear Gradients
<defs> <linearGradient id="pattern2" x1="0%" y1="100%" x2="100%" y2="0%"> <stop offset="0%" stop-color="yellow"/> <stop offset="40%" stop-color="red"/> <stop offset="80%" stop-color="blue"/> </linearGradient> </defs> <g> <rect width="150" height="150" x="50" y="50" fill="url(#pattern2)"/> </g>
Simple Radial Gradients
<defs> <radialGradient id="pattern1"> <stop offset="0%" stop-color="yellow"/> <stop offset="40%" stop-color="red"/> <stop offset="80%" stop-color="blue"/> </radialGradient> </defs>
<g> <rect width="150" height="150" x="50" y="50" fill="url(#pattern1)"/> </g>
Exercise Set Three
1) Create a linear gradient with 5 stops colors and display a rectangle with that linear gradient
2) Create a radial gradient with 5 stop colors and display an ellipse with that radial gradient
If you have extra time:3) Display a checkerboard with gradient effects
4) Display a cube with linear and radial gradients
Simple Transform Effects
<g> <rect width="150" height="150" x="50" y="50" fill="red"/> </g> <g transform="rotate(40)"> <rect width="150" height="150" x="50" y="50" fill="blue"/> </g> <g transform="scale(2,0.5)"> <rect width="150" height="150" x="50" y="50" fill="green"/> </g>
Exercise Set Four
1) Apply a scale() transform to an ellipse
2) Apply a skew() transform to an ellipse
3) Apply a rotate() transform to a rectangle
4) Apply a translate() transform to a rectangle
If you have extra time:5) Apply all transforms to an ellipse
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
Modular and Scalable CSS (1)
OOCSS: Object Oriented CSS
SMACSS: Scalable and Modular Architecture for CSS
DRY: Don’t Repeat Yourself CSS
BEM: Block, Element, Modifier
Modular and Scalable CSS (2)
#1 and #2 avoid id (prefer class) all share common goals they use different approaches provide general guidelines (not
absolute) try to understand underlying principles then take the relevant parts
BorderRadius2.html <!doctype html> <head> <meta charset="utf-8" /> <title>CSS Rounded Corners</title> <link href="BorderRadius2.css” rel="stylesheet"
type="text/css"> </head> <body> <div id="outer"> <img src="sample1.png" id="imgborder1” width="200" height="200"/> <img src="sample2.png" id="imgborder2” width="200" height="200"/> <img src="sample3.png" id="imgborder3” width="200" height="200"/> </div> </body> </html>
BorderRadius2.css #imgborder3 { -webkit-border-top-left-radius : 2em; -webkit-border-top-right-radius : 2em; -webkit-border-bottom-left-radius : 0.5em; -webkit-border-bottom-right-radius : 0.5em; border-top-left-radius : 5em; border-top-right-radius : 5em; border-bottom-left-radius : 2.5em; border-bottom-right-radius : 2.5em; } #imgborder1, #imgborder2 { -webkit-border-radius : 50%; border-radius : 10em 10em 10em 10em; }
LinearGradient1.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>CSS Linear Gradient Example</title> <link href="LinearGradient1.css" rel="stylesheet" type="text/css"> </head> <body> <div id="outer"> <p id="line1">line 1 with a linear gradient</p> <p id="line2">line 2 with a linear gradient</p> </div> </body> </html>
LinearGradient1.css #line1 { width: 50%; font-size: 32px; background-image: linear-gradient(to bottom,
#fff, #f00); border-radius: 4px; }
RadialGradient1.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>CSS Linear Gradient Example</title> <link href=”RadialGradient1.css” rel="stylesheet" type="text/css"> </head> <body> <div id="outer"> <div id="radial3">Text3</div> <div id="radial2">Text2</div> <div id="radial4">Text4</div> <div id="radial1">Text1</div> </div> </body> </html>
RadialGradient1.css #radial1 { font-size: 24px; width: 100px; height: 100px; position: absolute; top: 300px; left: 300px;
background: radial-gradient(farthest-side at 60% 55%, red, yellow, #400);
}
CSS3 Transforms: Examples rotate effect: rotate(45deg);rotate clockwise 45 degrees
scale effect: scale(2); make bigger (2 x horizontal and vertical)
Translate effect: translate(100px, 50px);Move right 100px and down 50px
skew effect: skew(10deg, 30deg);“twist” 10 deg/30 deg (horizontal/vertical)
A Scaled PNG (OneScale.html)<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <title>CSS Scale Transform</title><link href="Scale1.css” rel="stylesheet" type="text/css"></head><body> <div id="outer"> <img src="sample1.png" class="scaled" width="150" height="150"/> </div></body></html>
The CSS3 code (OneScale.css)
img.scaled:hover { -webkit-transform : scale(2); -transform : scale(2);}
What “Works” with CSS3?
Combine these with CSS3 in a Web Page: SVG and D3 (=Document Driven
Data=JS+SVG) HTML5 Canvas (bitmap and without a DOM)
For Web applications: jQuery (cross-browser and cross-platform) BackboneJS (MVP reduces spaghetti code) AngularJS (open source from Google) Basically any JavaScript-based toolkit
When CSS3 Alone isn’t Enough CSS3 can leverage the power of SVG:+ reference SVG documents via “url()”
• SVG can leverage CSS3 by:+ embedding CSS selectors in an SVG doc
use jQuery methods:+ the css() method for updating properties
• Use jQuery Mobile features:+ bindings to handle mouse/touch events
Exercise: PNGs with Transforms
Create an HTML5 Web page that:1) renders three PNGs
2) References a CSS3 stylesheet with: a) selectors for scale, rotate, and skew b) hover-based animation effect
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"></head><body><script> d3.select("body") .append("p") .text("Hello1 D3");</script> <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 ScatterChartcircles.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
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 2 Pocket Primer (2016)