D3.js – Zooming API ”; Previous Next Zooming helps to scale your content. You can focus on a particular region using the click-and-drag approach. In this chapter, we will discuss Zooming API in detail. Configuring API You can load the Zooming API directly from the “d3js.org” using the following script. <script src = “https://d3js.org/d3-color.v1.min.js”></script> <script src = “https://d3js.org/d3-dispatch.v1.min.js”></script> <script src = “https://d3js.org/d3-ease.v1.min.js”></script> <script src = “https://d3js.org/d3-interpolate.v1.min.js”></script> <script src = “https://d3js.org/d3-selection.v1.min.js”></script> <script src = “https://d3js.org/d3-timer.v1.min.js”></script> <script src = “https://d3js.org/d3-transition.v1.min.js”></script> <script src = “https://d3js.org/d3-drag.v1.min.js”></script> <script src = “https://d3js.org/d3-zoom.v1.min.js”></script> <body> <script> </script> </body> Zooming API Methods Following are some of the most commonly used Zooming API Methods. d3.zoom() zoom(selection) zoom.transform(selection, transform) zoom.translateBy(selection, x, y) zoom.translateTo(selection, x, y) zoom.scaleTo(selection, k) zoom.scaleBy(selection, k) zoom.filter([filter]) zoom.wheelDelta([delta]) zoom.extent([extent]) zoom.scaleExtent([extent]) zoom.translateExtent([extent]) zoom.clickDistance([distance]) zoom.duration([duration]) zoom.interpolate([interpolate]) zoom.on(typenames[, listener]) Let us go through all these Zooming API methods in brief. d3.zoom() It creates a new zoom behavior. We can access it using the script below. <script> var zoom = d3.zoom(); </script> zoom(selection) It is used to apply the zoom transformation on a selected element. For example, you can instantiate a mousedown.zoom behavior using the following syntax. selection.call(d3.zoom().on(“mousedown.zoom”, mousedowned)); zoom.transform(selection, transform) It is used to set the current zoom transform of the selected elements to the specified transform. For example, we can reset the zoom transform to the identity transform using the syntax below. selection.call(zoom.transform, d3.zoomIdentity); We can also reset the zoom transform to the identity transform for 1000 milliseconds using the following syntax. selection.transition().duration(1000).call(zoom.transform, d3.zoomIdentity); zoom.translateBy(selection, x, y) It is used to translate the current zoom transform of the selected elements by x and y values. You can specify x and y translation values either as numbers or as functions that returns numbers. If a function is invoked for the selected element, then it is passed through the current datum ‘d’ and index ‘i” for DOM. A sample code is defined below. zoom.translateBy(selection, x, y) { zoom.transform(selection, function() { return constrain(this.__zoom.translate( x = = = “function” ? x.apply(this, arguments) : x, y = = = “function” ? y.apply(this, arguments) : y ); } }; zoom.translateTo(selection, x, y) It is used to translate the current zoom transform of the selected elements to the specified position of x and y. zoom.scaleTo(selection, k) It is used to scale the current zoom transform of the selected elements to k. Here, k is a scale factor, specified as numbers or functions. zoom.scaleTo = function(selection, k) { zoom.transform(selection, function() { k = = = “function” ? k.apply(this, arguments) : k; }); }; zoom.scaleBy(selection, k) It is used to scale the current zoon transform of the selected elements by k. Here, k is a scale factor, specified either as numbers or as functions that returns numbers. zoom.scaleBy = function(selection, k) { zoom.scaleTo(selection, function() { var k0 = this.__zoom.k, k1 = k = = = “function” ? k.apply(this, arguments) : k; return k0 * k1; }); }; zoom.filter([filter]) It is used to set the filter to the specified function for zoom behavior. If the filter is not specified, it returns the current filter as shown below. function filter() { return !d3.event.button; } zoom.wheelDelta([delta]) The value of Δ is returned by the wheel delta function. If delta is not specified, it returns the current wheel delta function. zoom.extent([extent]) It is used to set the extent to the specified array points. If the extent is not specified, it returns the current extent accessor, which defaults to [[0, 0], [width, height]], where width is the client width of the element and height is its client height. zoom.scaleExtent([extent]) It is used to set the scale extent to the specified array of numbers [k0, k1]. Here, k0 is the minimum allowed scale factor. While, k1 is the maximum allowed scale factor. If extent is not specified, it returns the current scale extent, which defaults to [0, ∞]. Consider the sample code that is defined below. selection .call(zoom) .on(“wheel”, function() { d3.event.preventDefault(); }); The user can try to zoom by wheeling, when already at the corresponding limit of the scale extent. If we want to prevent scrolling on wheel input regardless of the scale extent, register a wheel event listener to prevent the browser default behavior. zoom.translateExtent([extent]) If the extent is specified, it sets the translate extent to the specified array of points. If extent is not specified, it returns the current translate extent, which defaults to [[-∞, -∞], [+∞, +∞]]. zoom.clickDistance([distance]) This method is used to set the maximum distance that the zoomable area can move between up and down, which will trigger a subsequent click event. zoom.duration([duration]) This method is used to set the duration for zoom transitions on double-click and double-tap to the specified number of milliseconds and returns the zoom behavior. If the duration is not specified, it returns the current duration, which defaults to 250 milliseconds, which is defined below. selection .call(zoom) .on(“dblclick.zoom”, null); zoom.interpolate([interpolate]) This method is used to interpolate for zoom transitions to the specified function. If interpolate is not specified, it returns the current interpolation factory, which defaults to d3.interpolateZoom. zoom.on(typenames[, listener]) If the listener is specified, it sets the event listener for the specified typenames and returns the zoom behavior. The typenames is a string containing one or more typename separated by whitespace. Each typename is a type, optionally followed by a period (.) and a name, such as zoom.one and zoom.second. The name allows multiple listeners to be registered for the same type. This type must be from one of the following − Start − after zooming begins (such as on mousedown). Zoom − after a change to the zoom transform (such as on mousemove). End − after zooming ends (such as on mouseup ). In the next chapter, we will discuss the different requests API in D3.js. Print Page Previous Next Advertisements ”;
Category: d3js
D3.js – Colors API
D3.js – Colors API ”; Previous Next Colors are displayed combining RED, GREEN and BLUE. Colors can be specified in the following different ways − By color names As RGB values As hexadecimal values As HSL values As HWB values The d3-color API provides representations for various colors. You can perform conversion and manipulation operations in API. Let us understand these operations in detail. Configuring API You can directly load API using the following script. <script src = “https://d3js.org/d3-color.v1.min.js”></script> <script> </script> Basic Operations Let us go through the basic color operations in D3. Convert color value to HSL − To convert color value to HSL, use the following Example − var convert = d3.hsl(“green”); You can rotate the hue by 45° as shown below. convert.h + = 45; Similarly, you can change the saturation level as well. To fade the color value, you can change the opacity value as shown below. convert.opacity = 0.5; Color API Methods Following are some of the most important Color API Methods. d3.color(specifier) color.opacity color.rgb() color.toString() color.displayable() d3.rgb(color) d3.hsl(color) d3.lab(color) d3.hcl(color) d3.cubehelix(color) Let us understand each of these Color API Methods in detail. d3.color(specifier) It is used to parse the specified CSS color and return RGB or HSL color. If specifier is not given, then null is returned. Example − Let us consider the following example. <script> var color = d3.color(“green”); // asign color name directly console.log(color); </script> We will see the following response on our screen − {r: 0, g: 128, b: 0, opacity: 1} color.opacity If we want to fade the color, we can change the opacity value. It is in the range of [0, 1]. Example − Let us consider the following example. <script> var color = d3.color(“green”); console.log(color.opacity); </script> We will see the following response on the screen − 1 color.rgb() It returns the RGB value for the color. Let us consider the following example. <script> var color = d3.color(“green”); console.log(color.rgb()); </script> We will see the following response on our screen. {r: 0, g: 128, b: 0, opacity: 1} color.toString() It returns a string representing the color according to the CSS Object Model specification. Let us consider the following example. <script> var color = d3.color(“green”); console.log(color.toString()); </script> We will see the following response on our screen. rgb(0, 128, 0) color.displayable() Returns true, if the color is displayable. Returns false, if RGB color value is less than 0 or greater than 255, or if the opacity is not in the range [0, 1]. Let us consider the following example. <script> var color = d3.color(“green”); console.log(color.displayable()); </script> We will see the following response on our screen. true d3.rgb(color) This method is used to construct a new RGB color. Let us consider the following example. <script> console.log(d3.rgb(“yellow”)); console.log(d3.rgb(200,100,0)); </script> We will see the following response on the screen. {r: 255, g: 255, b: 0, opacity: 1} {r: 200, g: 100, b: 0, opacity: 1} d3.hsl(color) It is used to construct a new HSL color. Values are exposed as h, s and l properties on the returned instance. Let us consider the following example. <script> var hsl = d3.hsl(“blue”); console.log(hsl.h + = 90); console.log(hsl.opacity = 0.5); </script> We will see the following response on the screen. 330 0.5 d3.lab(color) It constructs a new Lab color. The channel values are exposed as ‘l’, ‘a’ and ‘b’ properties on the returned instance. <script> var lab = d3.lab(“blue”); console.log(lab); </script> We will see the following response on the screen. {l: 32.29701093285073, a: 79.18751984512221, b: -107.8601617541481, opacity: 1} d3.hcl(color) Constructs a new HCL color. The channel values are exposed as h, c and l properties on the returned instance. Let us consider the following example. <script> var hcl = d3.hcl(“blue”); console.log(hcl); </script> We will see the following response on the screen. {h: 306.2849380699878, c: 133.80761485376166, l: 32.29701093285073, opacity: 1} d3.cubehelix(color) Constructs a new Cubehelix color. Values are exposed as h, s and l properties on the returned instance. Let us consider the following example. <script> var hcl = d3.hcl(“blue”); console.log(hcl); </script> We will see the following response on the screen, {h: 236.94217167732103, s: 4.614386868039719, l: 0.10999954957200976, opacity: 1} Working Example Let us create a new webpage – color.html to perform all the color API methods. The complete code listing is defined below. <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <h3>D3 colors API</h3> <script> var color = d3.color(“green”); console.log(color); console.log(color.opacity); console.log(color.rgb()); console.log(color.toString()); console.log(color.displayable()); console.log(d3.rgb(“yellow”)); console.log(d3.rgb(200,100,0)); var hsl = d3.hsl(“blue”); console.log(hsl.h + = 90); console.log(hsl.opacity = 0.5); var lab = d3.lab(“blue”); console.log(lab); var hcl = d3.hcl(“blue”); console.log(hcl); var cube = d3.cubehelix(“blue”); console.log(cube); </script> </body> </html> Now, request the browser and we will see the following response. Print Page Previous Next Advertisements ”;
D3.js – Animation
D3.js – Animation ”; Previous Next D3.js supports animation through transition. We can do animation with proper use of transition. Transitions are a limited form of Key Frame Animation with only two key frames – start and end. The starting key frame is typically the current state of the DOM, and the ending key frame is a set of attributes, styles and other properties you specify. Transitions are well suited for transitioning to a new view without a complicated code that depends on the starting view. Example − Let us consider the following code in “transition_color.html” page. <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <h3>Simple transitions</h3> <script> d3.select(“body”).style(“background-color”, “lightblue”) // make the background-color lightblue.transition() .style(“background-color”, “gray”); // make the background-color gray </script> </body> </html> Here, the Background color of the document changed from white to light gray and then to gray. The duration() Method The duration() method allows property changes to occur smoothly over a specified duration rather than instantaneously. Let us make the transition which takes 5 seconds using the following code. <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <h3>Simple transitions</h3> <script> d3.selectAll(“h3”).transition().style(“color”,”green”).duration(5000); </script> </body> </html> Here, the transitions occurred smoothly and evenly. We can also assign RGB color code value directly using the following method. d3.selectAll(“h3”).transition().style(“color”,”rgb(0,150,120)”).duration(5000); Now, each color number slowly, smoothly and evenly goes from 0 to 150. To get the accurate blending of in-between frames from the start frame value to the end frame value, D3.js uses an internal interpolate method. The syntax is given below − d3.interpolate(a, b) D3 also supports the following interpolation types − interpolateNumber − support numerical values. interpolateRgb − support colors. interpolateString − support string. D3.js takes care of using the proper interpolate method and in advanced cases, we can use the interpolate methods directly to get our desired result. We can even create a new interpolate method, if needed. The delay() Method The delay() method allows a transition to take place after a certain period of time. Consider the following code in “transition_delay.html”. <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <h3> Simple transitions </h3> <script> d3.selectAll(“h3”).transition() .style(“font-size”,”28px”).delay(2000).duration(2000); </script> </body> </html> Lifecycle of Transition Transition has a four-phased lifecycle − The transition is scheduled. The transition starts. The transition runs. The transition ends. Let us go through each of these one by one in detail. The Transition is scheduled A transition is scheduled when it is created. When we call selection.transition, we are scheduling a transition. This is also when we call attr(), style() and other transition methods to define the ending key frame. The Transition Starts A transition starts based on its delay, which was specified when the transition was scheduled. If no delay was specified, then the transition starts as soon as possible, which is typically after a few milliseconds. If the transition has a delay, then the starting value should be set only when the transition starts. We can do this by listening to the start event − d3.select(“body”) .transition() .delay(200) .each(“start”, function() { d3.select(this).style(“color”, “green”); }) .style(“color”, “red”); The Transition Runs When the transition runs, it repeatedly invoked with values of transition ranging from 0 to 1. In addition to delay and duration, transitions have easing to control timing. Easing distorts time, such as for slow-in and slow-out. Some easing functions may temporarily give values of t greater than 1 or less than 0. The Transition Ends The transition ending time is always exactly 1, so that the ending value is set exactly when the transition ends. A transition ends based on the sum of its delay and duration. When a transition ends, the end event is dispatched. Print Page Previous Next Advertisements ”;
D3.js – Selections
D3.js – Selections ”; Previous Next Selections is one of the core concepts in D3.js. It is based on CSS selectors. It allows us to select one or more elements in a webpage. In addition, it allows us to modify, append, or remove elements in a relation to the pre-defined dataset. In this chapter, we will see how to use selections to create data visualizations. D3.js helps to select elements from the HTML page using the following two methods − select() − Selects only one DOM element by matching the given CSS selector. If there are more than one elements for the given CSS selector, it selects the first one only. selectAll() − Selects all DOM elements by matching the given CSS selector. If you are familiar with selecting elements with jQuery, D3.js selectors are almost the same. Let us go through each of the methods in detail. The select() method The select() method selects the HTML element based on CSS Selectors. In CSS Selectors, you can define and access HTML-elements in the following three ways − Tag of a HTML element (e.g. div, h1, p, span, etc.,) Class name of a HTML element ID of a HTML element Let us see it in action with examples. Selection by Tag You can select HTML elements using its TAG. The following syntax is used to select the “div” tag elements, d3.select(“div”) Example − Create a page “select_by_tag.html” and add the following changes, Live Demo <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <div> Hello World! </div> <script> d3.select(“div”).text(); </script> </body> </html> By requesting the webpage through the browser, you will see the following output on the screen − Selection by Class name HTML elements styled using CSS classes can be selected by using the following syntax. d3.select(“.<class name>”) Create a webpage “select_by_class.html” and add the following changes − Live Demo <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <div class = “myclass”> Hello World! </div> <script> ad3.select(“.myclass”).text(); </script> </body> </html> By requesting the webpage through the browser, you will see the following output on the screen − Selection by ID Every element in a HTML page should have a unique ID. We can use this unique ID of an element to access it using the select() method as specified below. d3.select(“#<id of an element>”) Create a webpage “select_by_id.html” and add the following changes. Live Demo <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <div id = “hello”> Hello World! </div> <script> d3.select(“#hello”).text(); </script> </body> </html> By requesting the webpage through the browser, you will see the following output on the screen. Adding DOM Elements The D3.js selection provides the append() and the text() methods to append new elements into the existing HTML documents. This section explains about adding DOM elements in detail. The append() Method The append() method appends a new element as the last child of the element in the current selection. This method can also modify the style of the elements, their attributes, properties, HTML and text content. Create a webpage “select_and_append.html” and add the following changes − Live Demo <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <div class = “myclass”> Hello World! </div> <script> d3.select(“div.myclass”).append(“span”); </script> </body> </html> Requesting the webpage through browser, you could see the following output on the screen, Here, the append() method adds a new tag span inside the div tag as shown below − <div class = “myclass”> Hello World!<span></span> </div> The text() Method The text() method is used to set the content of the selected / appended elements. Let us change the above example and add the text() method as shown below. Live Demo <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <div class = “myclass”> Hello World! </div> <script> d3.select(“div.myclass”).append(“span”).text(“from D3.js”); </script> </body> </html> Now refresh the webpage and you will see the following response. Here, the above script performs a chaining operation. D3.js smartly employs a technique called the chain syntax, which you may recognize from jQuery. By chaining methods together with periods, you can perform several actions in a single line of code. It is fast and easy. The same script can also access without chain syntax as shown below. var body = d3.select(“div.myclass”); var span = body.append(“span”); span.text(“from D3.js”); Modifying Elements D3.js provides various methods, html(), attr() and style() to modify the content and style of the selected elements. Let us see how to use modify methods in this chapter. The html() Method The html() method is used to set the html content of the selected / appended elements. Create a webpage “select_and_add_html.html” and add the following code. Live Demo <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <div class = “myclass”> Hello World! </div> <script> d3.select(“.myclass”).html(“Hello World! <span>from D3.js</span>”); </script> </body> </html> By requesting the webpage through the browser, you will see the following output on the screen. The attr() Method The attr() method is used to add or update the attribute of the selected elements. Create a webpage “select_and_modify.html” and add the following code. Live Demo <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <div class = “myclass”> Hello World! </div> <script> d3.select(“.myclass”).attr(“style”, “color: red”); </script> </body> </html>
D3.js – Discussion
Discuss D3.js ”; Previous Next D3 stands for Data-Driven Documents. D3.js is a JavaScript library for manipulating documents based on data. D3.js is a dynamic, interactive, online data visualizations framework used in a large number of websites. D3.js is written by Mike Bostock, created as a successor to an earlier visualization toolkit called Protovis. This tutorial will give you a complete knowledge on D3.jsframework. This is an introductory tutorial, which covers the basics of Data-Driven Documents and explains how to deal with its various components and sub-components. Print Page Previous Next Advertisements ”;
D3.js – Timer API
D3.js – Timer API ”; Previous Next Timer API module is used to perform the concurrent animations with synchronized timing delay. It uses requestAnimationFrame for animation. This chapter explains Timer API module in detail. requestAnimationFrame This method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation. Configuring Timer We can easily load the timer directly from d3js.org by using the following script. <script src = “https://d3js.org/d3-timer.v1.min.js”></script> <script> var timer = d3.timer(callback); </script> Timer API Methods The Timer API supports the following important methods. All of these are explained in detail as follows. d3.now() This method returns the current time. d3.timer(callback[, delay[, time]]) This method is used to schedule a new timer and invokes the timer until stopped. You can set a numeric delay in MS, but it is optional otherwise, it defaults to zero. If time is not specified, it is considered as d3.now(). timer.restart(callback[, delay[, time]]) Restart a timer with the specified callback and optional delay and time. timer.stop() This method stops the timer, preventing subsequent callbacks. d3.timeout(callback[, delay[, time]]) It is used to stop the timer on its first callback. Callback is passed as the elapsed time. d3.interval(callback[, delay[, time]]) It is invoked on a particular time delay interval. If delay is not specified, it takes the timer time. Example Create a webpage “timer.html” and add the following script to it. <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <h3> Timer API </h3> <script> var timer = d3.timer(function(duration) { console.log(duration); if (duration > 150) timer.stop(); }, 100); </script> </body> </html> We will see the following response on the screen. Print Page Previous Next Advertisements ”;
D3.js – Useful Resources
D3.js – Useful Resources ”; Previous Next The following resources contain additional information on D3.js. Please use them to get more in-depth knowledge on this. Useful Video Courses Full Stack Development With Vue JS 2 And Spring Boot 54 Lectures 3.5 hours Senol Atac More Detail Node js for Course for beginners + Game project 27 Lectures 2.5 hours Laurence Svekis More Detail ReactJS Course : Learn React JS From Scratch Best Seller 61 Lectures 4.5 hours Skillbakery More Detail JavaScript Deep Dive: Explore JS (For Beginners-to-Advanced) 129 Lectures 5.5 hours TELCOMA Global More Detail WebGL 2D/3D Programming and Graphics Rendering For The Web 29 Lectures 4 hours Frahaan Hussain More Detail React JS and .NET Core Web API Full Stack Master Course 21 Lectures 3.5 hours Vinay Kumar More Detail Print Page Previous Next Advertisements ”;
D3.js – Transitions API
D3.js – Transitions API ”; Previous Next D3 Transitions take a selection of elements and for each element; it applies a transition to a part of the current definition of the element. Configuring API You can configure the transition API using the following script. <script src = “https://d3js.org/d3-color.v1.min.js”></script> <script src = “https://d3js.org/d3-dispatch.v1.min.js”></script> <script src = “https://d3js.org/d3-ease.v1.min.js”></script> <script src = “https://d3js.org/d3-interpolate.v1.min.js”></script> <script src = “https://d3js.org/d3-selection.v1.min.js”></script> <script src = “https://d3js.org/d3-timer.v1.min.js”></script> <script src = “https://d3js.org/d3-transition.v1.min.js”></script> <script> </script> Transition API Methods Let us go through the Transition API methods in detail. Selecting Elements Let us discuss the various selecting elements in detail. selection.transition([name]) − This method is used to return a new selection transition with the name. If a name is not specified, it returns null. selection.interrupt([name]) − This method is used to interrupt the selected elements of the transition with the name and is defined below. selection.interrupt().selectAll(“*”).interrupt(); d3.interrupt(node[, name]) − This method is used to interrupt the transition of the specified name on the specified node. d3.transition([name]) − This method is used to return a new transition with the specified name. transition.select(selector) − This method is used to select the first element that matches the specified selector and returns a transition on the resulting selection, which is defined below. transition .selection() .select(selector) .transition(transition) transition.selectAll(selector) − This method is used to select all the elements that matches the specified selector and returns a transition on the resulting selection. It is defined below − transition .selection() .selectAll(selector) .transition(transition) transition.filter(filter) − This method is used to select the elements matching the specified filter, they are defined below. transition .selection() .filter(filter) .transition(transition) transition.merge(other) − This method is used to merge the transition with other transition. It is defined below. transition .selection() .merge(other.selection()) .transition(transition) transition.transition() − This method is used to return a new transition on the selected elements. It is scheduled to start when the transition stops. The new transition inherits this transition’s name, duration and easing. Example − Let us consider the following example. d3.selectAll(“.body”) .transition() // fade to yellow. .style(“fill”, “yellow”) .transition() // Wait for five second. Then change blue, and remove. .delay(5000) .style(“fill”, “blue”) .remove(); Here, the body fades to yellow and starts just five seconds before the last transition. d3.active(node[, name]) − This method is used to return the transition on the specified node with the name. Timing Methods Let us go through the transition timing API methods in detail. transition.delay([value]) − This method is used to set the transition delay to the specified value. If a function is evaluated for each selected element, it is passed to the current datum ‘d’ and index ‘i”, with the context as the current DOM element. If a value is not specified, returns the current value of the delay for the first (non-null) element in the transition. It is defined below, transition.delay(function(d, i) { return i * 10; }); transition.duration([value]) − This method is used to set the transition duration to the specified value. If a value is not specified, returns the current value of the duration for the first (non-null) element in the transition. transition.ease([value]) − This method is used to ease the transition value for selected elements. The easing function is invoked for each frame of the animation and passed the normalized time ‘t’ in the range [0, 1]. If a value is not specified, it returns the current easing function for the first (non-null) element in the transition. In the next chapter, we will discuss the drag and drop concept in d3.js. Print Page Previous Next Advertisements ”;
D3.js – Paths API
D3.js – Paths API ”; Previous Next Paths are used to draw Rectangles, Circles, Ellipses, Polylines, Polygons, Straight Lines, and Curves. SVG Paths represent the outline of a shape that can be Stroked, Filled, Used as a Clipping Path, or any combination of all three. This chapter explains Paths API in detail. Configuring Paths You can configure the Paths API using the script below. <script src = “https://d3js.org/d3-path.v1.min.js”></script> <script> </script> Paths API Methods Some of the most commonly used Paths API methods are briefly described as follows. d3.path() − This method is used to create a new path. path.moveTo(x, y) − This method is used to move the specified x and y values. path.closePath() − This method is used to close the current path. path.lineTo(x, y) − This method is used to create a line from current point to defined x,y values. path.quadraticCurveTo(cpx, cpy, x, y) − This method is used to draw a quadratic curve from current point to the specified point. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y) − This method is used to draw a bezier curve from current point to the specified point. path.arcTo(x1, y1, x2, y2, radius) − This method is used to draw a circular arc from the current point to a specified point (x1, y1) and end the line between the specified points (x1, y1) and (x2, y2). path.arc(x, y, radius, startAngle, endAngle[, anticlockwise]) − This method is used to draw a circular arc to the specified center (x, y), radius, startAngle and endAngle. If anticlockwise value is true then the arc is drawn in the anticlockwise direction, otherwise it is drawn in the clockwise direction. path.rect(x, y, w, h) − This method is used to create new sub path containing just the four points (x, y), (x + w, y), (x + w, y + h), (x, y + h). With these four points connected by straight lines marks the subpath as closed. Equivalent to context.rect and uses SVG’s “lineto” commands. path.toString() − Returns the string representation of this path according to SVG’s path data specification. Example Let us draw a simple line in D3 using path API. Create a webpage linepath.html and add the following changes in it. Live Demo <!DOCTYPE html> <meta charset = “UTF-8”> <head> <title>SVG path line Generator</title> </head> <style> path { fill: green; stroke: #aaa; } </style> <body> <svg width = “600” height = “100”> <path transform = “translate(200, 0)” /> </svg> <script src = “https://d3js.org/d3.v4.min.js”></script> <script> var data = [[0, 20], [50, 30], [100, 50], [200, 60], [300, 90]]; var lineGenerator = d3.line(); var pathString = lineGenerator(data); d3.select(”path”).attr(”d”, pathString); </script> </body> </html> Now, request the browser and we will see the following result. Print Page Previous Next Advertisements ”;
D3.js – Introduction to SVG
D3.js – Introduction to SVG ”; Previous Next SVG stands for Scalable Vector Graphics. SVG is an XML-based vector graphics format. It provides options to draw different shapes such as Lines, Rectangles, Circles, Ellipses, etc. Hence, designing visualizations with SVG gives you more power and flexibility. Features of SVG Some of the salient features of SVG are as follows − SVG is a vector based image format and it is text-based. SVG is similar in structure to HTML. SVG can be represented as a Document object model. SVG properties can be specified as attributes. SVG should have absolute positions relative to the origin (0, 0). SVG can be included as is in the HTML document. A Minimal Example Let us create a minimal SVG image and include it in the HTML document. Step 1 − Create a SVG image and set width as 300 pixel and height as 300 pixel. <svg width = “300” height = “300”> </svg> Here, the svg tag starts an SVG image and it has width and height as attributes. The default unit of the SVG format is pixel. Step 2 − Create a line starting at (100, 100) and ending at (200, 100) and set red color for the line. <line x1 = “100” y1 = “100” x2 = “200” y2 = “200” style = “stroke:rgb(255,0,0);stroke-width:2″/> Here, the line tag draws a line and its attributes x1, y1 refers to the starting point and x2, y2 refers to the ending point. The style attribute sets color and thickness of the line using the stroke and the stroke-width styles. x1 − This is the x-coordinate of the first point. y1 − This is the y-coordinate of the first point. x2 − This is the x-coordinate of the second point. y2 − This is the y-coordinate of the second point. stroke − Color of the line. stroke-width − Thickness of the line. Step 3 − Create a HTML document, “svg_line.html” and integrate the above SVG as shown below − Live Demo <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> <style> body { font-family: Arial; } </style> </head> <body> <div id = “svgcontainer”> <svg width = “300” height = “300”> <line x1 = “100” y1 = “100” x2 = “200” y2 = “200” style = “stroke:rgb(255,0,0); stroke-width:2″/> </svg> </div> <p></p> <p></p> </body> </html> The above program will yield the following result. SVG Using D3.js To create SVG using D3.js, let us follow the steps given below. Step 1 − Create a container to hold the SVG image as given below. <div id = “svgcontainer”></div> Step 2 − Select the SVG container using the select() method and inject the SVG element using the append() method. Add the attributes and styles using the attr() and the style() methods. var width = 300; var height = 300; var svg = d3.select(“#svgcontainer”) .append(“svg”).attr(“width”, width).attr(“height”, height); Step 3 − Similarly, add the line element inside the svg element as shown below. svg.append(“line”) .attr(“x1”, 100) .attr(“y1”, 100) .attr(“x2”, 200) .attr(“y2”, 200) .style(“stroke”, “rgb(255,0,0)”) .style(“stroke-width”, 2); The complete code is as follows − Live Demo <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> <style> body { font-family: Arial; } </style> </head> <body> <div id = “svgcontainer”> </div> <script language = “javascript”> var width = 300; var height = 300; var svg = d3.select(“#svgcontainer”) .append(“svg”) .attr(“width”, width) .attr(“height”, height); svg.append(“line”) .attr(“x1”, 100) .attr(“y1”, 100) .attr(“x2”, 200) .attr(“y2”, 200) .style(“stroke”, “rgb(255,0,0)”) .style(“stroke-width”, 2); </script> </body> </html> The above code yields the following result. Rectangle Element A rectangle is represented by the <rect> tag as shown below. <rect x = “20” y = “20” width = “300” height = “300”></rect> The attributes of a rectangle are as follows − x − This is the x-coordinate of the top-left corner of the rectangle. y − This is the y-coordinate of the top-left corner of the rectangle. width − This denotes the width of the rectangle. height − This denotes the height of the rectangle. A simple rectangle in SVG is defined as explained below. <svg width = “300” height = “300”> <rect x = “20” y = “20” width = “300” height = “300” fill = “green”></rect> </svg> The same rectangle can be created dynamically as described below. Live Demo <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <div id = “svgcontainer”></div> <script> var width = 300; var height = 300; //Create SVG element var svg = d3.select(“#svgcontainer”) .append(“svg”) .attr(“width”, width) .attr(“height”, height); //Create and append rectangle element svg.append(“rect”) .attr(“x”, 20) .attr(“y”, 20) .attr(“width”, 200) .attr(“height”, 100) .attr(“fill”, “green”); </script> </body> </html> The above code will yield the following result. Circle Element A circle is represented by the <circle> tag as explained below. <circle cx = “200” cy = “50” r = “20”/> The attributes of circle are as follows − cx − This is the x-coordinate of the center of the circle. cy − This is the y-coordinate of the center of the circle. r − This denotes the radius of the circle. A simple circle in SVG is described below. <svg width = “300” height = “300”> <circle cx = “200” cy = “50” r = “20” fill = “green”/> </svg> The same circle can be created dynamically as described below. Live Demo <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <div id = “svgcontainer”></div> <script> var width = 300; var height = 300; //Create SVG element var svg = d3.select(“#svgcontainer”) .append(“svg”) .attr(“width”, width) .attr(“height”, height); //Append circle svg.append(“circle”) .attr(“cx”, 200) .attr(“cy”, 50) .attr(“r”, 20) .attr(“fill”, “green”); </script> </body> </html> The above code will yield the following result. Ellipse Element The SVG Ellipse element is represented by the <ellipse> tag as explained below. <ellipse cx = “200” cy = “50” rx = “100” ry = “50”/> The attributes of an ellipse are as follows − cx − This is the x-coordinate of the center of the ellipse. cy − This is the y-coordinate of the center of