Learning Raphaël JS Vector Graphics

Over 70 code examples to create vector graphics and data visualizations!

Damian Dawber

130 Pages

49950 Reads



PDF Format

5.69 MB

Java Script

Download PDF format

  • Damian Dawber   
  • 130 Pages   
  • 03 Mar 2015
  • Page - 1

    www.it-ebooks.info read more..

  • Page - 2

    Learning Raphaël JS V ector Graphics Over 70 code examples to create vector graphics and data visualizations! Damian Dawber BIRMINGHAM - MUMBAI www.it-ebooks.info read more..

  • Page - 3

    Learning Raphaël JS V ector Graphics Copyright © 2013 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the read more..

  • Page - 4

    Credits Author Damian Dawber Reviewers Charles Thomas Lee Turver Acquisition Editor Mary Jasmine Nadar Commissioning Editor Harsha Bharwani Technical Editor Jalasha D'costa Project Coordinator Sneha Modi Proofreader Mario Cecere Indexer Rekha Nair Production Coordinator Shantanu Zagade Cover Work Shantanu Zagade www.it-ebooks.info read more..

  • Page - 5

    About the Author Damian Dawber is a web developer working on medium- to large-scale e-commerce websites and bespoke web and mobile applications. He works with both frontend and server-side technologies having had exposure to a wide range of projects working on behalf of small and medium enterprises through to FTSE 100 companies. He started his career after being exposed read more..

  • Page - 6

    About the Reviewers as a trainee accountant and soldier, Charles Thomas supplied a software solution for a company he worked for as a laboratory supervisor in 1990. When he was made unemployed by his company in 1992, he completed further software training (HNC in Computer Studies in 1994). Since 1994, he has always been engaged in projects that are on the "bleeding edge read more..

  • Page - 7

    www.PacktPub.com You might want to visit www.PacktPub.com to your book. Did you know that Packt offers eBook versions of every book published, with PDF www.PacktPub. com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com , you can also read a collection of free read more..

  • Page - 8

    Table of Contents Preface 1 Chapter 1: The Graphical Web 5 Vector drawing on the Web 6 Vector drawing libraries 7 Working with Raphaël rather than SVG directly 9 Applications of Raphaël 9 Downloading Raphaël 10 Creating Raphaël JavaScript applications 11 Project structure and optimization 11 Summary 11 Chapter 2: Canvas coordinates 15 Drawing basic shapes 16 Applying strokes 20 Other attributes read more..

  • Page - 9

    Table of Contents [ ii ] Embedding custom fonts 29 The moveto command 34 The lineto commands 35 The closepath command 37 Quadratic Bézier curves 38 Cubic Bézier curves 41 Drawing arcs 43 Utility methods for working with paths 46 Element.getTotalLength() 46 Element.getPointAtLength(length) 47 Element.getSubpath(from, to) 48 Catmull-Rom curves 49 Summary 50 Chapter 4: Transformations and Event read more..

  • Page - 10

    Table of Contents [ iii ] Chapter 5: Vector Animation 65 Basic animation 66 Animating paths 67 Animation easing 70 Built-in easing formulas 70 Custom easing using the cubic Bézier format 71 Animating transformations 72 Custom attributes 73 Animation along a path 76 Pausing and resuming animation 78 Summary 79 Chapter 6: Downloading Inkscape 82 Getting started with Inkscape 82 Inkscape's read more..

  • Page - 11

    Table of Contents [ iv ] Updating the timer 106 The animate helper method 107 Iterating over our timers and starting the animation 108 Facebook usage by year 108 Golden tweets 109 The future of Raphaël 110 Milestones 110 Long term goals 110 Summary 111 www.it-ebooks.info read more..

  • Page - 12

    Preface Learning Raphaël JS Vector Graphics takes you on a tour of the Raphaël JavaScript library and its potential applicability in today's online landscape. While it is a "mini", it is by no means limited. Coverage is given to all of the library's main facets and applications thereof and on completion of this book you will be able to create vector drawings and read more..

  • Page - 13

    Preface [ 2 ] Who this book is for This book is for any and all developers with an interest in frontend technologies. It is perfectly suited to those with a desire to create interactive applications or vector drawings in the web browser. It is assumed that the reader has a basic understanding of or familiarity with JavaScript. Conventions different kinds of read more..

  • Page - 14

    Preface [ ] Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to feedback@packtpub.com , and mention the book title through the subject of read more..

  • Page - 15

    Preface [ 4 ] Errata Although we have taken every care to ensure the accuracy of our content, mistakes the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this http://www.packtpub. com/support , selecting your book, clicking on the errata submission form link, read more..

  • Page - 16

    The Graphical Web The ability to draw graphics in the web browser is important in today's online landscape. While the need to effectively represent information has long existed in the empirical sciences, mathematics, and print media, it has taken on a new lease of life since the advent of the Web. With the colossal volumes of data that we now generate and the existence read more..

  • Page - 17

    The Graphical Web [ 6 ] The library's creator and JavaScript virtuoso, Dmitry Baranovskiy, has done a great job documenting Raphaël at http://raphaeljs.com/ and we will make extensive reference to the documentation throughout the course of this book in order to concoct quality bespoke vector graphics in the browser. In this chapter we will: Discuss vector drawing on the Web Look read more..

  • Page - 18

    Chapter 1 [ 7 ] pixel, level. Your display is, after all, the sum of many millions of these points. The difference between bitmap and vector graphics is that in the case of vector graphics, the rendering is done at the very last moment. Scaling up a bitmap means creating new pixels based on the existing ones whereas with vector graphics, pixels are created at the read more..

  • Page - 19

    The Graphical Web [ ] Raphaël is particularly well suited to creating bespoke vector graphics since it primitive vector graphics and offers scope for working with existing SVG images. D3.js makes creating data visualizations straightforward owing to its API being very much oriented to mathematical operations and data manipulation but does not the lower levels. Paper.js uses the HTML5 Canvas for read more..

  • Page - 20

    Chapter 1 [ 9 ] Working with Raphaël rather than SVG directly Browser support aside, one good reason for using Raphaël over writing raw SVG is that it makes vector drawing easier. Take for example, drawing a rectangle and animating its width from 50 pixels to 100 pixels using raw SVG: <rect x="10" y="10" width="50" height="30"> read more..

  • Page - 21

    The Graphical Web [ 10 ] Raphaël is particularly well suited to cartography as the library affords us the ability to add interactivity to DOM elements and to scale graphics up and down without the loss of quality. A nice example of this can be found at http://raphaeljs.com/ australia.html , where an interactive choropleth map of Australia is demoed (we will look at creating choropleth maps read more..

  • Page - 22

    Chapter 1 [ 11 ] Creating Raphaël JavaScript applications The most important aspect of learning how to utilize a new technology is understanding the concepts driving it. Code samples will be used where appropriate throughout this book but reams of unnecessary code will be omitted in favor of concentrating on the core aspects of the task at hand. Where appropriate, you should read more..

  • Page - 23

    www.it-ebooks.info read more..

  • Page - 24

    Basic Drawing with Raphaël Raphaël supports three fundamental types of graphics elements: shapes, images, they can be a combination of lines, curves, and paths. Vector graphics are by their we will create a number of interesting drawings based on them. Images are either bitmap images (such as .png or .jpeg ) or existing SVG images, and can be manipulated by Raphaël in many of the read more..

  • Page - 25

    Basic Drawing with Raphaël [ 14 ] Strictly speaking, a viewport is any rectangular viewing region. We will always refer to the browser window as the viewport and our drawing region as the canvas (not to be confused with the HTML5 Canvas). We can create a canvas using the Raphael constructor as follows: var paper = Raphael(50, 100, 500, 300); Downloading the example read more..

  • Page - 26

    Chapter 2 [ 15 ] More commonly we will want to use an existing DOM element as a container for our canvas rather than the viewport. In this case, the left-/right- (x-/y-) offsets are not required as the canvas will always be rendered at the top-left corner of the element. Consider the element: <div id="my-canvas"></div> We would create our 500px wide, 300px read more..

  • Page - 27

    Basic Drawing with Raphaël [ 16 ] Note that graphics drawn at negative x or y points will be drawn starting from outside of the visible region of the canvas meaning that they will be partially or fully hidden from the viewer as illustrated in the following diagram: Drawing basic shapes Raphaël provides the rect, circle, and ellipse methods for drawing basic shapes. These read more..

  • Page - 28

    Chapter 2 [ 17 ] Both rectangles are shown in the following diagram. Note that drawing is from the top-left corner of the rectangle in the positive x and y directions: The syntax for a circle (http://raphaeljs.com/reference.html#Paper.circle) is: Paper.circle(x, y, r); While the x and y coordinates of a rectangle describe its top-left point, for a center point. The read more..

  • Page - 29

    Basic Drawing with Raphaël [ ] It should be clear that the circle is in fact just a special case of the ellipse where x-radius is equal to y-radius . The resultant circles and ellipses are shown in the following diagram: Raphaël is well documented at http://raphaeljs.com/reference.html. For complete coverage of the methods used throughout this book, you are strongly advised to make read more..

  • Page - 30

    Chapter 2 [ 19 ] In order give an element a background, fill attribute. #rrggbb or the #rgb shorthand, the rgb(r, g, b) string or a color keyword, for example, navy var rect = paper.rect(200, 50, 200, 100); rect.attr({fill: '#000'}); var square = paper.rect(450, 50, 50, 50); square.attr({fill: 'rgb(0, 0, 0)'}); var circle = paper.circle(100, 100, 50); circle.attr({fill: read more..

  • Page - 31

    Basic Drawing with Raphaël [ 20 ] bg_pattern.png as shown x and y: Applying strokes Elements can have a number of different stroke attributes. The most common are the stroke and stroke-width attributes. The stroke attribute takes a string value for stroke-width is a number in pixels. The following code has the effect of applying a 10px-wide lime-green stroke to a read more..

  • Page - 32

    Chapter 2 [ 21 ] You will notice in some of the earlier examples in this chapter that even though we did not apply attributes to them they were still stroked. This is because the default stroke-width value is 1px. To remove the stroke when drawing shapes, we must always specify a stroke-width value of 'none' . Some other useful stroke attributes are stroke-dasharray read more..

  • Page - 33

    Basic Drawing with Raphaël [ 22 ] opacity The opacity of elements can be set to a value between 0 (complete transparency) and using the stroke-opacity and fill-opacity attributes: An unfortunate side effect of strokes always being drawn centrally is that half of the stroke-opacity has limited applicability. Specifying 'stroke-opacity': 0.5 in combination with a stroke color read more..

  • Page - 34

    Chapter 2 [ ] This has the effect of only showing the part of the circle that is overlapped by the rectangular clipping region '20 20 80 80' : Applying gradients rather than specifying a color string on the fill attribute, we specify a string of the following form in order to create linear gradients: <angle>-<color>[-<color>[:<offset>]]*-<color> The read more..

  • Page - 35

    Basic Drawing with Raphaël [ 24 ] This draws a rectangle with a linear gradient from red to black at an angle of 0 '90-#f00-#000' , where this time the gradient is drawn at an angle of 90 degrees: Note that the angle of drawing is x axis going running blue to white: Linear gradients can be composed of any number of colors and the points at which read more..

  • Page - 36

    Chapter 2 [ 25 ] This has the effect of creating a rainbow-style pattern as shown in the following Technically, since the difference between each offset is equal for all colors (20 percent), we could have omitted the offset values from the string in the previous example. The gradient described by the following expression yields the same result: read more..

  • Page - 37

    Basic Drawing with Raphaël [ 26 ] This describes a circle with a gradient from white at the center to black at its edges: As with linear gradients, we can for each. The string 'r#fff-#f00-#00f:90-#000' , for example, creates a radial gradient from white to red to blue at an offset of 90 percent to black at the edges. The point from which a radial gradient is read more..

  • Page - 38

    Chapter 2 [ 27 ] Note that radial gradients cannot be applied to a Path element (see Chapter 3, Drawing Paths) owing to a bug in VML and so only really applies to the basic shapes we cover in this chapter. Grouping elements There are times when we wish to apply the same attributes, transformations, or animations to multiple elements. We can group elements in read more..

  • Page - 39

    Basic Drawing with Raphaël [ ] The result is shown as follows: Working with text Drawing text in the canvas rather than as HTML markup with CSS styling allows us to animate and transform it in the same way as we would for other shapes. Text is created using the text method and its properties (such as size and font-family ) text method text parameter is our read more..

  • Page - 40

    Chapter 2 [ 29 ] text-anchor , on each text element. The text-anchor attribute has the effect of determining whether the origin x point on the text method Embedding custom fonts The font converter and renderer Cufón has been superseded by @font-face for paths and integrate seamlessly with Raphaël meaning that we can manipulate such fonts in many of the same ways that read more..

  • Page - 41

    Basic Drawing with Raphaël [ ] We print text using our custom font onto our canvas as follows: var text = paper.print( 50, 50, 'Vi veri veniversum vivus vici', paper.getFont('Pacifico'), 38 ); This draws custom text with a font size of 38px onto our canvas at the point (50, 50). The getFont method simply references the name of read more..

  • Page - 42

    Drawing Paths The ability to draw and manipulate paths is an extremely powerful feature of Raphaël. In the previous chapter we drew basic shapes based on the paths' geometric properties such as width, height, and radius. Paths allow us to draw representing the outline of the shape itself. Paths, such as basic shapes, are elements meaning that user interaction, painting, transformations, and read more..

  • Page - 43

    Drawing Paths [ ] Path drawing concepts The process of drawing with a pen on paper can be broken down into the following steps: 1. You place your pen at a particular point on a piece of paper. 2. You press and move the pen freely from this point to another point. 3. You keep your pen at this point or lift up the pen and place it at another point on the read more..

  • Page - 44

    Chapter 3 [ ] Finally, we create an arc back to the point (100, 180) to complete the path: The example of the arbelos demonstrates the drawing of a single path, where we did not lift up the pen at any point during the drawing process. Were we to lift up the pen, the subsequent drawing would technically create subpaths on the main path element. In the example, read more..

  • Page - 45

    Drawing Paths [ ] This path string is used in drawing the arbelos of the previous section. Drawing is started using the M command and subsequent arcs are then drawn using the a command. We draw paths in Raphaël using the path method, which accepts either a path string or an array as a parameter. Arrays are usually a more convenient and more readable var xStart = read more..

  • Page - 46

    Chapter 3 [ ] (x, y) pair moves the pen to the point (50, 50) on our canvas as we would expect. However, the second (x, y) pair has the effect of drawing a line to the point (100, 150), as well as moving the current point. This behavior means that the moveto command can be used to draw polygons. The following code draws a triangle with vertices at (250, read more..

  • Page - 47

    Drawing Paths [ ] Command Parameters Example L or l (x, y)+ L 100 100 H or h x+ H 75 V or v y+ V -75 By way of example, a line from the point (10, 10) to the point (75, 100) would be drawn as follows: var line = paper.path(['M', 10, 10, 'L', 75, 100]); Note that because we use the uppercase command, L , the line is drawn from the point (0, 0) and not read more..

  • Page - 48

    Chapter 3 [ ] Note that in JavaScript, the trigonometric functions expect a value of angle measured in radians to be passed so we have used the rad utility method on the Raphael object to convert 60 degrees into radians. The closepath command The closepath command draws a straight line from the current point to the starting point of the current subpath. In the example read more..

  • Page - 49

    Drawing Paths [ ] The closepath command character is Z and does not accept any parameters. Since in the previous example we drew a straight line back to the end point, we could instead close the path using the closepath command as follows: var hexagon = paper.path( ['M', 250, 15, 'l', sideLength, 0, x, y, -x, y, -sideLength, 0, read more..

  • Page - 50

    Chapter 3 [ ] There are two quadratic Bézier curve commands, the syntax for which is given here: Command Parameters Example Q or q (x1, y1, x, y)+ Q 100 50 200 250 T or t (x y)+ T 400 250 The Q command (or q for relative points) describes a curve drawn from the current point on a path to the point (x, y) using (x1, y1) as a control point. For example, consider the read more..

  • Page - 51

    Drawing Paths [ 40 ] As with the other commands we have encountered so far, parameters can be repeatable, which allows us to draw multiple connected quadratic Bézier curves. Consider the following code: paper.path([ 'M', 50, 150 'Q', 225, 20, 400, 150, 575, 20, 750, 150 ]); This has the effect of drawing a second curve from (400, 150) to the read more..

  • Page - 52

    Chapter 3 [ 41 ] The principles behind drawing cubic Bézier curves are similar to those for quadratic Bézier curves except that cubic Bézier curves have two control points. Again, in order to appreciate how cubic Bézier curves are drawn, you should take a look at the animated demo at http://www.jasondavies.com/animated-bezier/ . The cubic Bézier curve's path (highlighted in red in the screenshot) starts from P0 and heads read more..

  • Page - 53

    Drawing Paths [ 42 ] The C command requires that we specify both control points. The following code has the effect of drawing a curve from the point (200, 20) to (200, 120) via the control points (400, 140) and (400, 180). Note also that we have closed the path and applied paper.path([ 'M', 200, 20, 'C', 400, 140, 400, 180, 200, 120, read more..

  • Page - 54

    Chapter 3 [ ] The hardest thing about working with Bézier curves is deciding where to control points. Figuring these out is usually achieved by one of the following: Trial and error Mathematical computation Using a graphics package such as Inkscape to aid you in drawing Drawing arcs The syntax for drawing arcs is the most involved of all the drawing commands. This is because when read more..

  • Page - 55

    Drawing Paths [ 44 ] The syntax for arc drawing is given in the following table: Command Parameters Example A or a (rx, ry, x-rotation, large-arc-flag, sweep-flag, x, y)+ a 25 50 0 1 0 100 200 The following table describes each of the individual parameters: Parameters Description rx and ry Since an arc is a portion of an ellipse, it has a radius in x and y x-rotation read more..

  • Page - 56

    Chapter 3 [ 45 ] Were we to specify a large-arc-flag value equal to 0, the minor arc of the ellipse passing through (50, 60) and (50, 140) would be drawn as shown: Were we to specify sweep-flag equal to 0, for example, for the path described by M 350,60 a 150,80 0 1 0 0,80 in the case of the major arc or M 350,60 a 150,80 0 0 0 0,80 in read more..

  • Page - 57

    Drawing Paths [ 46 ] The following diagram describes a minor arc (large-arc-flag = 0 ) drawn in a counterclockwise direction: Utility methods for working with paths Raphaël provides a number of convenient utility methods for working with paths. We will demonstrate these methods by example. Element.getTotalLength() By combining a major arc and a cubic Bézier curve, we can draw a bowling pin shape as follows: read more..

  • Page - 58

    Chapter 3 [ 47 ] Element.getPointAtLength(length) We can get the x and y coordinates of any point along the length of a path using the getPointAtLength method. This method returns an object with x and y attributes. Using the example of a bowling pin from the previous section, we plot two circular points at the one-eighth and one-half of the total length of the read more..

  • Page - 59

    Drawing Paths [ ] Given a path element, the getSubpath method calculates the path string for a subsection of its path. Given two points on a path, it returns the path string that describes the original path between just those two points. Consider the cubic Bézier curve between the points (100, 100) and (300, 100) with anchor points at (100, 200) and (300, 0): var path read more..

  • Page - 60

    Chapter 3 [ 49 ] Catmull-Rom curves In those cases where we need to draw a curve that passes through a prescribed set of points, a Catmull-Rom curve is often appropriate. Catmull-Rom curves are commonly used in charting (that is, in data plotting) and gaming (for example, to Raphaël provides a path command to facilitate the drawing of Catmull-Rom curves. The syntax for drawing Catmull-Rom read more..

  • Page - 61

    Drawing Paths [ 50 ] their values to our path array: for(var i = 1, num = data.length; i < num; i+=1) { path.push(data[i].x); path.push(data[i].y); } var curve = paper.path( path ); The resultant curve drawn using the path command is shown here: Summary We have now covered all the main drawing methods in Raphaël and you should experimenting with the path commands read more..

  • Page - 62

    Transformations and Event Handling Having spent the past two chapters drawing static graphics, we will now start to look at how we can transform them and how we can interact with them in the browser. When you create an element in Raphaël, you are effectively creating a Document Object Model (DOM) object. Like the DOM objects you are already familiar with elements drawn read more..

  • Page - 63

    Transformations and Event Handling [ 52 ] handling We perform transformations in Raphaël using the transform method on elements, a sequence of transformations to take place on a particular element. You can also transform elements and sets using the transform attribute. This is often convenient when we are changing multiple attributes at the same time. You will see examples of read more..

  • Page - 64

    Chapter 4 [ ] Translation First off, consider drawing a triangle and creating a copy of it using the clone method: var triangle = paper.path("M 150 20 l 100 160 l -200 0 z").attr({ 'stroke-dasharray': '- ', 'stroke-width': 5 }); var triangleCopy = triangle.clone(); // Clones our object triangleCopy.attr({ 'stroke-dasharray': '' }); When cloned, the copied read more..

  • Page - 65

    Transformations and Event Handling [ 54 ] Here we have combined the commands. In this instance, the transformations are mutually independent meaning that the case of each command is unimportant. However, consider rotation about a point: triangleCopy.transform("t 100 0 r 180 220 100"); x and then rotates it by 180 degrees clockwise. Our rotation point (220, 100) is not the point read more..

  • Page - 66

    Chapter 4 [ 55 ] Scaling Scaling can be performed either equally on all points about a scaling point or a factor in x and y. The scaling for the t 300 0 s 0.5 transformation scales all points by 0.5 times their original about the center point of the element as shown: Scaling in x and y by the t 310 0 s 1.2 0.5 transformation string scales the read more..

  • Page - 67

    Transformations and Event Handling [ 56 ] transformation on an element: salinon.mouseover(function() { this.transform('R 180'); }); salinon.dblclick(function() { this.transform('r 45'); }); salinon.mouseout(function() { this.transform(''); }); This has the effect of: When moving your mouse over the element, it is rotated by 180 degrees When double-clicking the element, it is read more..

  • Page - 68

    Chapter 4 [ 57 ] on a single click, translates the element 300px in x and also rotates it by 180 degrees clockwise. The second transformation, invoked on an additional 200px and rotated 45 degrees clockwise relative to the current rotation. Note that the additional 100px translation in x is in the negative x-direction, this is because we take the previous 180 read more..

  • Page - 69

    Transformations and Event Handling [ ] Working with matrices A matrix is a rectangular array of elements arranged in rows and columns. It is so a 3-by-2 matrix, for example, would be: Each element in a matrix can be thought of as a component that maps some point to another point. The point (x, y), for example, can be mapped to (p, q) as follows: space. The new read more..

  • Page - 70

    Chapter 4 [ 59 ] Using transformation matrices to perform shear The matrix for shear transformations is as follows: Sx and Sy represent the factor by which x and y points are sheared respectively. For example, applying the transformation string "m 1 0 0.5 1 0 0" (Sx = 0.5, Sy = 0) to a square has the effect of transforming it into a rhombus in x: Usually read more..

  • Page - 71

    Transformations and Event Handling [ 60 ] The drag-and-drop functionality The drag-and-drop functionality is a powerful feature of Raphaël. In particular, we are offered a good deal of control over drag events, which affords us the ability to create more usable applications. The Element.drag() method The drag method of an element has the following syntax: Element.drag( onmove, read more..

  • Page - 72

    Chapter 4 [ 61 ] Note that dx and dy are commonly used in mathematics to refer to small changes in x and y. Every time that the onmove event handler is called, its dx and dy parameters will have values representing a small change in each direction. Dragging by example Consider for example dragging a square. reference to its start x and y positions in read more..

  • Page - 73

    Transformations and Event Handling [ 62 ] Dropping elements At the end of dragging an element, we can perform checks to see where it has ended up relative to other elements. A drop is essentially a check to see whether our element falls within some particular set of bounds. containing all points of an element. By checking to see whether two bounding boxes overlap read more..

  • Page - 74

    Chapter 4 [ ] While the isBBoxIntersect method is convenient, we sometimes need to know whether or not all points on an element are inside another. Going back to the previous example, we could check to see whether the top-left vertex and bottom-right vertex of our square's bounding box fall within the target bounding box using the isPointInsideBBox method like so: read more..

  • Page - 75

    Transformations and Event Handling [ 64 ] Summary In this chapter we have covered a lot of ground relating to both event handling and transformations. You should be familiar with some of the ways that we are able to interact with our drawings and transform them at will. We are in a prime position now to look at truly bringing our drawings to life by animating them read more..

  • Page - 76

    Vector Animation Till now we have looked at drawing static graphics and interacting with and transforming them instantaneously. Animation affords us the ability to change graphics with regard to time, that is, we can modify the attributes of a vector graphic over some non-zero time interval. Prior to the emergence of the JavaScript frameworks of the early 2000s, animation was read more..

  • Page - 77

    Vector Animation [ 66 ] Animation is accomplished using the animate method of an element. The method Parameter Type Description attributes Object Key-value pair attributes as per the Element. attr() method duration Number The number of milliseconds that the duration should last for easing (optional) String A string describing the rate of change of an attribute with regard to time read more..

  • Page - 78

    Chapter 5 [ 67 ] Likewise, a rectangle at (100, 50) is animated to a point (400, 100) in x and y with increased width, reduced opacity, and a larger stroke-width as follows: var rectangle = paper.rect(100, 50, 20, 50).attr({ fill: '#345' }); rectangle.animate({ opacity: 0.6, x: 400, y: 100, width: 100, 'stroke-width': 10 read more..

  • Page - 79

    Vector Animation [ ] The star is a polygon whose lines overlap. This makes for an interesting effect when when clicked initializes a path animation as follows: var square = paper.rect(500, 100, 50, 50).attr({ 'fill': '#09c', cursor: 'pointer' }); square.click(function() { star.animate({ path: [ 'M', 100, 180, read more..

  • Page - 80

    Chapter 5 [ 69 ] 350, 130, 400, 250, 'H', 50, 'z' ]; var pathEnd = [ 'M', 50, 250, 'R', 100, 130, 150, 220, 200, 200, 250, 100, 300, 200, 350, 180, 400, 250, 'H', 50, 'z' ]; var curve = paper.path(pathStart).attr({ 'stroke-width': 0, 'stroke-linejoin': 'round' read more..

  • Page - 81

    Vector Animation [ 70 ] Animation easing Easing describes how the value of an attribute varies with regard to time. By default, the value of an attribute changes consistently—that is, linearly—over the course of an animation but by specifying a particular easing type, we can change the way in which the attribute is animated. Consider the following graph that demonstrates read more..

  • Page - 82

    Chapter 5 [ 71 ] In this instance, the attribute value is path , which is quickly animated to its end point and then back again until change in the path with regard to time is illustrated here: The format for CSS3 transitions describing animation easing can be used to 'cubic-bezier(point1_x, point1_y, point2_x, point2_y)' x and y positions of anchor points describing a read more..

  • Page - 83

    Vector Animation [ 72 ] The CSS3 syntax that describes this path is cubic-bezier(0.1, 0.97, 0.08, 0.03) . This was generated using a useful tool at http://www.roblaplaca.com/ examples/bezierBuilder/ that allows you to visually construct your custom easing path and get the cubic-bezier values for the resultant easing. By way of example consider two circles, one of which is read more..

  • Page - 84

    Chapter 5 [ ] to the y animation object and then passed this to the animate method on the square when clicked. This can re-use them. Animation using custom attributes Raphaël facilitates advanced animation via custom attributes. Custom attributes can be used to apply, or animate, multiple attributes on a particular element based on Custom attributes function that returns a set of read more..

  • Page - 85

    Vector Animation [ 74 ] custom attribute, popDensity , for a visual representation of this data as per the aforementioned rules: paper.customAttributes.popDensity = function(population, density) { var radius = 25 + (25 * population), fillColor = 'hsb(0, 0,' + (1 - density) + ')'; return { fill: fillColor, r: read more..

  • Page - 86

    Chapter 5 [ 75 ] popDensity: [country.population, country.density], 'stroke-width': 4 }); paper.text(currentX, 225, country.name).attr({ 'font-size': 14 }); currentX += 100; } During each iteration of the loop, the population density attributes are determined from our data objects and are drawn to our read more..

  • Page - 87

    Vector Animation [ 76 ] }); circle.animate({ popDensity: [country.population, country.density] }, 1000, 'easeOut'); paper.text(currentX, 225, country.name).attr({ 'font-size': 14 }); currentX += 100; } You will notice when running are Animation along a path Over the course of an animation, attribute values read more..

  • Page - 88

    Chapter 5 [ 77 ] paper.customAttributes.pathFactor = function(distance) { var point = path.getPointAtLength(distance * pathLength); var dx = point.x, dy = point.y; return { transform: ['T', dx, dy] }; }; We always return an absolute transformation that uses the (x, y) point on the path to determine where on read more..

  • Page - 89

    Vector Animation [ ] When this code is executed, you will see that our circle is animated along our path forever, taking four seconds to traverse the path from the start point and back again. Pausing and resuming animation We have not yet looked at the ability to pause and resume animations. Consider, in the example of animating along a handlers on our circle as part of read more..

  • Page - 90

    Chapter 5 [ 79 ] Summary Over the course of this chapter we have looked at the concepts driving animation and the different ways in which we can attribute elements to attributes. You should now be in a position to comfortably create, transform, and animate vector graphics using the Raphaël library and should have no trouble utilizing the Raphaël documentation to build on what we have read more..

  • Page - 91

    www.it-ebooks.info read more..

  • Page - 92

    Working with Existing SVGs Most designers use a mixture of raster and vector graphics in their projects and so are familiar with vector graphics editors such as Adobe Illustrator and Inkscape. The usefulness of these tools has grown considerably in recent years inline with advances in digital media—in particular, designers need to be able to create resolution- independent graphics read more..

  • Page - 93

    Working with Existing SVGs [ ] Inkscape Inkscape is an open source SVG editor whose feature set is similar to that of Adobe Illustrator. It is used by many designers given that: It is open source and actively maintained / developed There are a good number of tutorials available online It has a comprehensive feature set It conforms to the W3C standards SVG Inkscape also has read more..

  • Page - 94

    Chapter 6 [ ] 2. Choose the circle. 3. Click-and-drag anywhere on your canvas. 4. When releasing your mouse, your circle will look as follows: Notice the anchor points on the circle. The leftmost point is used to control the width of the circle, the topmost point controls the height while the rightmost point is used to change the end point. Click-and-drag on the rightmost read more..

  • Page - 95

    Working with Existing SVGs [ ] The result of dragging outside of the circle by an angle of a few degrees is shown in the following screenshot: the constituent objects. Click on File | Document Properties | Page and then expand the Resize and heights for the document. Clicking on Resize page to drawing or selection will resize the page and the dimensions of the read more..

  • Page - 96

    Chapter 6 [ ] 3. Create a new layer by clicking on the + symbol on the layers pane. 4. Select all objects in the previous layer. 5. Choose Layer | Move Selection to Layer Above. 6. Delete the previous layer. The result is as follows: Arguably the best tool we have at our disposal is the pen tool, which is used to draw Bézier curve paths: 1. Select the pen tool read more..

  • Page - 97

    Working with Existing SVGs [ ] You will notice that each which the curve is curved as shown in the following screenshot: to the start point anchor point: www.it-ebooks.info read more..

  • Page - 98

    Chapter 6 [ ] Inkscape comes with a number of tutorials at Help | Tutorials. Inspecting paths Since we're familiar with supplying raw path string data to the path method in Raphaël, it goes without saying that we can copy a path string from an SVG and easy to work with and manipulating multiple paths can be cumbersome but this approach of working with existing SVGs does give us complete read more..

  • Page - 99

    Working with Existing SVGs [ ] If we take this path and use it in Raphaël as follows: var initialPath = 'M 197,94.46 ' + 'A 98.5,94.5 0 1 1 167.39,26.92 L 98.5,94.46 z'; var pac = paper.path(initialPath); pac.attr({fill: '#09c', 'stroke-width': 0}); Then it is drawn onto our canvas as shown: Going back into Inkscape, move the arc anchor point so as to close the read more..

  • Page - 100

    Chapter 6 [ ] We can achieve an interesting effect here with relatively little effort using path animation, animating from the former "open mouth" path to the latter "closed move that determines the x and y coordinates of our pac element based on rotation (which is initialized to zero to begin with): var rotation = 0; var move = function() { var read more..

  • Page - 101

    Working with Existing SVGs [ 90 ] SVG to Raphaël conversion tools There are a number of good SVGs to Raphaël JS converters out there that will convert an SVG image into Raphaël automatically and without too much pain. Ready Set Raphaël Ready Set Raphaël ( http://www.readysetraphael.com ) is a web-based SVG converter that allows you to upload an image and grab the resultant Raphaël code. It read more..

  • Page - 102

    Chapter 6 [ 91 ] The result of rendering the Other converters It is worth mentioning that there are a number of other good SVG to Raphaël works best for you. Charles Thomas's SVG to HTML converter (http://www.irunmywebsite.com/ raphael/SVGTOHTML_LIVE.php ) converts all primitive shapes to paths and ensures that all paths use absolute coordinates while the converter at read more..

  • Page - 103

    Working with Existing SVGs [ 92 ] Choropleth maps Choropleth maps are maps that show some particular area or region with an associated measurement or statistic. They are commonly used in cartography to depict population densities and similar metrics and are used regularly to visualize The following image, compiled using the https://commons.wikimedia.org/wiki/File:World_population_density_map. read more..

  • Page - 104

    Chapter 6 [ ] You can convert the aforementioned image using the Ready Set Raphael converter and import the resultant JavaScript into your HTML document. When running this code, you will see that the converter does a really good job of maintaining the paths and associated attributes. all drawn on the resultant map. These regions have the following populations where the resultant read more..

  • Page - 105

    Working with Existing SVGs [ 94 ] named shading brightness varies. This will have the effect of shading the countries according to their population sizes: rsr.customAttributes.shading = function(population, min, max, total) { var brightness = 1 - ((population - min) / (max - min)); return { fill: 'hsb(0, 0, ' + brightness + ')' read more..

  • Page - 106

    Chapter 6 [ 95 ] You can see that the north-east region—which has the lowest population—is colored white while the south-east region—which has the largest population—is colored black. One unfortunate effect of London having a population size that is nearly as large as that of the south-east region of the country is that it is impossible to distinguish between the read more..

  • Page - 107

    Working with Existing SVGs [ 96 ] Open source SVGs There are a number of SVGs available via the Open Clip Art Library at http://openclipart.org . The site features an excellent SVG editor that allows download them. Summary You should now be comfortable working with the existing SVGs in the context of your Raphaël-driven projects. You should have a basic understanding of Inkscape read more..

  • Page - 108

    Creating a Suite of Social Media Visualizations We have now covered all of the main facets of the Raphaël JavaScript library and over the course of this chapter we will look at creating data visualization demos based on social media statistics. Data visualization has really boomed in recent years. The number of infographics and data-related expositions online continue to grow as we read more..

  • Page - 109

    Creating a Suite of Social Media Visualizations [ ] In this section we will create an interactive visualization similar to a histogram the number of social network users to the total world population (six billion). It will use a common technique of highlighting icons to indicate the proportion of users relative to all world citizens when the relevant social network is read more..

  • Page - 110

    Chapter 7 [ 99 ] When a social media icon is clicked on, the number of highlighted persons will be courtesy of komodomedia.com and are distributed along with the source code accompanying this book. Using jQuery You will notice in the markup of the previous section that we have included the jQuery JavaScript library. This will be used to facilitate DOM interaction read more..

  • Page - 111

    Creating a Suite of Social Media Visualizations [ 100 ] var usage = { facebook: 1000000000, twitter: 500000000, flickr: 50000000, linkedin: 150000000, myspace: 50000000, googleplus: 400000000, orkut: 100000000, lastfm: 50000000 }; Drawing people icons paper variable. Based on the default width and height of the icons read more..

  • Page - 112

    Chapter 7 [ 101 ] var yTranslation = (bBox.height + 4) * j; path.transform(['T', xTranslation, yTranslation]); people.push(path); } } In the given code, we iterate over i columns and j rows. We draw the icon using the path method and then get its bounding box in order to ascertain the width and height of read more..

  • Page - 113

    Creating a Suite of Social Media Visualizations [ 102 ] We then get the class name of the element that was clicked and use it to get the number of users for this particular social network: var className = $(this).attr('class'); var numPeople = Math.ceil( people.length * (usage[className] / 6000000000) ); Since the class name maps to a usage value stored in our read more..

  • Page - 114

    Chapter 7 [ ] keyPerson.transform(['T', 0, bBox.height * 8]); paper.text( bBox.width + 10, (bBox.height * 8) + 18, '= 50 million people' ).attr('text-anchor', 'start'); The position of this person path on our canvas is arbitrary. We place it at eight times the height of the paths bounding box so that it appears just below our six rows of read more..

  • Page - 115

    Creating a Suite of Social Media Visualizations [ 104 ] Getting started which we will draw four animated arc paths on page load. We will write our JavaScript in tweets-by-time.js : <h1>Tweets with respect to time</h1> <p>There are approximately 3,000 tweets every ...</p> <div id="tweets-timed"></div> <script type="text/javascript" read more..

  • Page - 116

    Chapter 7 [ 105 ] interval: 1000, total: 3000, text: '~ 3,000 tweets per second' }, // ... This code is truncated for the sake of brevity. For the full code you should download the source code accompanying this book. The subtend custom attribute The extent to which an arc is curved, or subtended, is read more..

  • Page - 117

    Creating a Suite of Social Media Visualizations [ 106 ] The counts custom attribute Our visualization will display the number of tweets as text based on the proportion (expressed as a factor between 0 and 1) of the animation that has passed and the total counts custom attribute to return this ratio of time elapsed to total tweets as text as follows: read more..

  • Page - 118

    Chapter 7 [ 107 ] The animate helper method The purpose of the animate function is to animate: The arc from its initial arc path to The number of tweets counted over the time interval elapsed In the code given here, we animate our arc to subtend 360 degrees and our text counts as a proportion of the total number of tweets: function animate(i, cx, cy, r, interval) read more..

  • Page - 119

    Creating a Suite of Social Media Visualizations [ ] Iterating over our timers and starting the animation To initialize the animation, we iterate counts text with an initial value of 0 positioned at the center-x and center-y point of our arc. We then run our update function on each timer, which has the effect of animating the arcs in a recursive manner as we have read more..

  • Page - 120

    Chapter 7 [ 109 ] The supplementary material for this visualization is available at http:// raphaeljsvectorgraphics.com/book/supplementary/facebook-usage-by-year . Golden tweets Twitter published an article at the end of 2012 discussing some of the tweets that were re-tweeted the highest number of times. These have been marketed as golden tweets given the high levels of participation that read more..

  • Page - 121

    Creating a Suite of Social Media Visualizations [ 110 ] The future of Raphaël The current maintainer of Raphaël, Tomás Alabés, kindly contacted me with information pertaining to the future of the library. Going forward, we expect increased adoption of the library and changes are being put in place to enable more open source collaboration of Raphaël. Milestones The Raphaël project read more..

  • Page - 122

    Chapter 7 [ 111 ] Summary capabilities of the Raphaël library and have gained an understanding of some of the ways in which it can be used and the approaches taken to drawing vector graphics and visualizing data. You are reminded to explore the library's documentation and experiment with all of its available features and invest your time in researching the concepts driving your future read more..

  • Page - 123

    www.it-ebooks.info read more..

  • Page - 124

    Index Symbols <animate> element 9 A 58 animate helper method 107 animate method 107 animation about 66, 67 along path 76 attributes parameter 66 callback parameter 66 custom attributes, using 73-77 duration parameter 66 easing parameter 66 pausing 78 resuming 78 animation easing about 70 built-in easing formulas 70, 71 ease in out 70 ease out 70 linear read more..

  • Page - 125

    [ 114 ] downloading Raphaël 10 drag-and-drop functionality about 60 dragging by example 61, 62 Element.drag() method 60 onend event handler 60 onmove event handler 60 onstart event handler 60 drawing context about 13-15 canvas coordinates 15, 16 drop 62 E easing 70 Ebocs 9 Element.drag() method 60 element.getPointAtLength(length) 47 element.getSubpath(from, to) 48 read more..

  • Page - 126

    [ 115 ] P Paper.js 7 path animation 67-69 path command 50 path drawing commands 33 concepts 32, 33 path drawing commands about 33 closepath command 37, 38 lineto commands 35, 36 moveto command 34 pathFactor attribute 77 path inspection about 87 from existing SVG image 89 87- 89 paths utility methods 46 PFB 29 29 Printer Font Binary. See PFB print read more..

  • Page - 127

    [ 116 ] using, for shear performance 59 transformations animating 72, 73 transformation string 51 transform method 56 TrueType. See TTF TTF 29 tweets about 103 animate helper method 107 animation, starting 108 by time data 104 counts custom attribute 106 starting with 104 subtend custom attribute 105 timers, iterating 108 timer, updating 106 U utility read more..

  • Page - 128

    Thank you for buying Learning Raphaël JS V ector Graphics About Packt Publishing Mastering phpMyAdmin for Effective MySQL Management" in April 2004 and subsequently continued to specialize in publishing Our books and publications share the experiences of your fellow IT professionals in adapting and customizing today's systems, applications, and frameworks. Our solution based books give read more..

  • Page - 129

    Instant RaphaelJS Starter ISBN: 978-1-78216-985-7 Paperback: 62 pages Get to grips with RaphaelJS - a powerful cross-browser compatible vector graphics library, to create interactive 2D graphics and animations with ease 1. Learn something new in an Instant! A short, fast, focused guide delivering immediate results 2. Create cross-browser imageless read more..

  • Page - 130

    Sencha Touch Mobile JavaScript Framework ISBN: 978-1-84951-510-8 Paperback: 316 pages Build web applications for Apple iOS and Google mobile framework 1. Learn to develop web applications that look and feel native on Apple iOS and Google Android touchscreen devices using Sencha Touch through examples 2. Design resolution-independent and graphical representations read more..

Write Your Review