Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
HTML5 Graphing and Data Visualization Cookbook
HTML5 Graphing and Data Visualization Cookbook

HTML5 Graphing and Data Visualization Cookbook: Get a complete grounding in the exciting visual world of Canvas and HTML5 using this recipe-packed cookbook. Learn to create charts and graphs, draw complex shapes, add interactivity, work with Google maps, and much more.

eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

HTML5 Graphing and Data Visualization Cookbook

Chapter 2. Advanced Drawing in Canvas

  • Drawing arcs

  • Drawing curves with a control point

  • Creating a Bezier curve

  • Integrating images into our art

  • Drawing with text

  • Understanding pixel manipulation

Introduction


This is the last chapter where we will dig deep into canvas as the remaining chapters will focus on building charts and interactivity.

In this chapter, we will continue to master our skills with canvas by adding curves, images, text, and even pixel manipulation to our tool belt.

Drawing arcs


There are three types of curves we can create in canvas—using the arc, quadratic curves, and Bezier curves. Let's get started.

Getting ready

If you recall in Chapter 1, Drawing Shapes in Canvas, in our first recipe we used the arc method to create perfect circles. The arc method is much more than just that. We can actually create any partial curve in a circular shape. If you don't recall drawing circles, I strongly encourage you to scan through Chapter 1, Drawing Shapes in Canvas again, and while you are there, you will find the template for creating the HTML documents as well. We are exclusively going to focus on the JavaScript code in this recipe.

How to do it...

Let's jump into it and create our first noncircle that has curves:

  1. Access the pacman canvas element and fetch its width and height by using the following code snippet:

    var canvas = document.getElementById("pacman");
    var wid = canvas.width;
    var hei = canvas.height;
  2. Create a radian variable (one degree in radians):

    var radian...

Drawing curves with a control point


If the world was just two points with a perfect arc this would be the end of the book, but alas or lucky for us, there are still many more complex shapes to learn and explore. There are many curves that are not perfectly aligned curves. Till now all the curves that we created were part of a perfect circle, but not any more. In this recipe, we will explore quadratic curves. The quadratic curves enable us to create curves that are not circular, by adding a third point—a controller to control the curve. You can easily understand this by looking at the following diagram:

A quadratic curve is a curve that has one control point. Consider the case when creating a line, we draw it between two points (A and B in this illustration). When we want to create a quadratic curve, we use an external gravity controller that defines the direction of the curve while the middle line (the dotted line) defines how far will the curve reach.

Getting ready

As done in previous recipes...

Creating a Bezier curve


We've just learned that with the quadratic curve we have one control point. Although we can do many things with one control point, we don't really have full control over the curve. So let's take it one step further by adding one more control point. Adding a second control point actually adds the relationship between these two points as well making it three control factors. If we include the actual anchor points (we have got two of them), we end up with five points that control the shape of the curve. That does sound complicated; it's because the more control we get the more complicated it is to actually understand how it works. It's really not easy to figure out complicated curves by code alone and as such we actually use other tools to help us figure out the right curves.

To prove the preceding point, we can find a very complex shape and start with that one (don't worry, later on in this recipe, we will practice on a very simple shape to make the concept clear). We...

Integrating images into our art


Lucky for us, we don't need to start from scratch always and we can leave the more complex art for external images. Let's figure out how we can integrate images into our canvas.

Getting ready

We've been in a flag theme in this chapter and getting another flag under our belt sounds real good to me right now. So let's turn our heads to Haiti and get their flag up and running. To create this flag, we need to have the image of the symbol that is placed in the center of the flag.

In the source files, you will find an image of the center graphic (at img/haiti.png). By the way, when integrating art into canvas it's always best to avoid resizing the image whenever possible via code to preserve the image quality.

How to do it...

We will prepare the background to match the flag and then put the entire image above it in the center of the canvas/flag:

  1. Follow the basic steps that we need to access the canvas. Set the width, height, and the actual context:

    var canvas = document...

Drawing with text


I agree, we've been working on some complicated things. Now, its time for us to lay back, kick off the shoes, and do something a bit easier.

Getting ready

The good news is, if you are on this page, you should already know the basics of getting a canvas up and running. So there isn't much more that you need to do besides picking the font, size, and position of your text.

Note

Here, we aren't covering how you can embed fonts that aren't created within JavaScript, but instead, via CSS, we will use a basic font and hope for the best in this sample.

How to do it...

In this example, we are going to create a text field. In this process, we are going to use gradients and shadows for the first time. Perform the following steps:

  1. Gain access to the canvas 2D API:

    var canvas = document.getElementById("textCanvas");
      var wid = canvas.width;
      var hei = canvas.height;
    
      var context = canvas.getContext("2d");
  2. Create a gradient style and fill the background with it:

    var grd = context.createLinearGradient...

Understanding pixel manipulation


Now that you have mastered drawing in canvas, it's time for us to turn to a new aspect of working with canvas. In canvas, you can manipulate pixels. It's not only a vector drawing tool, but a very smart pixel editor (raster).

Getting ready

Now that we are about to start reading data that is present on the canvas, we need to understand how security works when it comes to pixels. In an effort to protect content that isn't yours, there are security issues involved in working with data that isn't hosted on the same host as yours. We will not cover these security issues in this section and will be always working with images in the same domain as our code (or all locally).

Your first step is to find an image that you wish to work with (I've added an old image of my own into the source files). In this sample, we will recreate a pixel fade-out animation—really cool and useful for slides.

How to do it...

Let's get our code working and then break it down to see how it works...

Left arrow icon Right arrow icon

Key benefits

  • Build interactive visualizations of data from scratch with integrated animations and events
  • Draw with canvas and other html5 elements that improve your ability to draw directly in the browser
  • Work and improve existing 3rd party charting solutions such as Google Maps

Description

The HTML5 canvas tag makes creating any plot shape easy, all you have to do then is fill it with exciting visualizations written in JavaScript or using other visualization tools. "HTML5 Graphing and Data Visualization Cookbook" is the perfect break into the world of Canvas, charts, and graphs in HTML5 and JavaScript. In this book we will go through a journey of getting to know the technology by creating and planning data-driven visualizations. This cookbook is organized in a linear, progressive way so it can be read from start to finish, as well as be used as a resource for specific tasks.This book travels through the steps involved in creating a fully interactive and animated visualization in HTML5 and JavaScript. You will start from very simple "hello world"ù samples and quickly dive deeper into the world of graphs and charts in HTML5. Followed by learning how canvas works and carrying out a group of tasks geared at taking what we learned and implementing it in a variety of chart types. With each chapter the content becomes more complex and our creations become more engaging and interactive.Our goal is that by the end of this book you will have a strong foundation; knowing when to create a chart on your own from scratch and when it would be a good idea to depend on other APIs.We finish our book in our last two chapters exploring Google maps and integrating everything we learnt into a full project.

Who is this book for?

You don't need to have a background in HTML5 or Canvas but you do need to have a basic understanding of how HTML works and know how to code in any language (preferably in JavaScript). In this book we will not explain how to learn to code but how to create projects and how to plan and execute them in the process.

What you will learn

  • Creating graphics in Canvas 2D and draw complex shapes
  • Building most of the common charts through step-by-step recipes
  • Adding interactivity to canvas elements and create your own JavaScript animation engine
  • Discovering many fantastic charting solutions and learn how to deal with their capabilities and how to change them as well
  • Learning how to work with Google maps , Google Charts, and Google Docs API
  • Integrating your data into live data, xml driven data, objects, and strings

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 23, 2012
Length: 344 pages
Edition : 1st
Language : English
ISBN-13 : 9781849693714
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 23, 2012
Length: 344 pages
Edition : 1st
Language : English
ISBN-13 : 9781849693714
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 99.97
Responsive Web Design with HTML5 and CSS3
€32.99
HTML5 Graphing and Data Visualization Cookbook
€41.99
Data Visualization: a successful design process
€24.99
Total 99.97 Stars icon
Banner background image

Table of Contents

10 Chapters
Drawing Shapes in Canvas Chevron down icon Chevron up icon
Advanced Drawing in Canvas Chevron down icon Chevron up icon
Creating Cartesian-based Graphs Chevron down icon Chevron up icon
Let's Curve Things Up Chevron down icon Chevron up icon
Getting Out of the Box Chevron down icon Chevron up icon
Bringing Static Things to Life Chevron down icon Chevron up icon
Depending on the Open Source Sphere Chevron down icon Chevron up icon
Playing with Google Charts Chevron down icon Chevron up icon
Using Google Maps Chevron down icon Chevron up icon
Maps in Action Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(10 Ratings)
5 star 60%
4 star 40%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Bill Ferster Sep 08, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Ben Fhala's HTML Graphing and Data Visualization Cookbook is a nice tutorial on how to create simple data visualizations using the HTML5 cocktail of JavaScript, the new HTML5 Canvas drawing options, and even using some external resources, such as Google's Visualization toolkit, Google Maps, and InfoVis.I was given a printed copy of the book and access to the online version by the publisher, PACKT Publishing, presumably because they had seen my book Interactive Visualization: Insight through Inquiry (2013, MIT Press) and I find this book to be a good practical complement to my own. Fhala's style is casual, clear and informative, and he relies on progressively introducing new concepts using code snippets that are fully explained in the text that follows.The first section of the book introduces drawing vector graphics using the HTML5 Canvas element. He does this by guiding the reader through the creation of a number of small programs that create the national flags of a number of counties, starting off with the simple rising sun of Japan to Canada's more complex maple leaf.There are sections on more advanced drawing topics, such a drawing Bezier curves, shadows and glows, and a good section on manipulating the screen on the pixel level for very basic image processing techniques.I like how he introduces simple charting, by building a series of popular Cartesian graphs directly using the Canvas without using any outside resources at first. He begins by defining the data structures required to represent the data to be graphed and progressively moves from bar charts, through scatter graphs to pie charts. The simple trigonometry needed is well explained, even the recursive algorithms needed to draw sophisticated tree maps are clearly described.The last section introduces the idea of using external web-based resources, such as, such as Google's Visualization toolkit, Google Maps, and InfoVis instead of drawing all the elements by hand and includes a section on implementing Google Maps as well.All in all, Ben Fhala's HTML Graphing and Data Visualization Cookbook does a good job of introducing the uninitiated into the word of interactive visualization. It's a shame he didn't extend his readers into the world of D3-based visualizations, but this is great first entry for those new to the field.Bill FersterUniversity of Virginia
Amazon Verified review Amazon
William Springer Sep 01, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Although I've been using HTML5 for a few years now, I haven't yet done much with the Canvas, the new drawing element. Having started, it reminds me of nothing so much as moving the turtle around in the old Logo programming language.In HTML5 Graphing and Data Visualization Cookbook, we start out by learning to create basic shapes in Canvas, with the gimmick of creating various national flags. This takes up only the first two chapters of the book, as it is presumed that the reader is already comfortable with HTML and JavaScript; the remaining eight chapters involve creating and using maps, graphs, and charts, both simple and animated. Towards the end of the book, we actually get into using the Google Maps API to overlay our data onto a world map.In each chapter, we start by typing in some new code and run it; after that, the book discusses what the code is doing. I liked the format because you see results right away - each code segment is relatively short - and then after seeing what happens, you see how it works. I also liked the little mathematical explanations and programming asides that pop up here and there. The chapter organization also makes it easy to jump to the section of the book you're interested in, so I think this will make a good reference.There were two things that irritated me about this book. The first was that the spacing in code is a little odd, with extra spaces where I wouldn't expect to see them and no space where I do expect one. This doesn't affect how the code works, but it's a little distracting. The book is also written in a fairly informal manner, complete with smileys; at times I felt like I was reading blog posts rather than a professional programming book. That said, neither of those really takes away from the usability of the book, and are more a matter of personal preference than anything else. For the topic this book covers, I haven't seen anything better.Disclosure: I received a free review copy of this book for Vulcan Ears Book Reviews (vulcanears.com), where this review originally appeared.
Amazon Verified review Amazon
Pavel Gerega Aug 14, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is the go to source for HTML5 graphing and data visualization. The author explains what is about to happen in the tutorial, creates the code, and then takes you step by step through the code explaining it all which is really important in understanding what exactly is going on. The wording is perfect; not too technical and dry but not too watered down either.The visuals help a lot and the different sections in the book make it easy to see what's where. I've never played around with the canvas element before picking up this book and I had no trouble jumping right in and following along with the tutorials and code in this book but I did have HTML and CSS knowledge previous to reading the book with was helpful.I was amazed at all the different things that was possible to do with the canvas element. If you know HTML but want to explore the canvas element in depth, I highly recommend this book. Interesting read and definitely worth it!
Amazon Verified review Amazon
Matt West Apr 01, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is easily the best book I have seen for coverage of the Canvas API.The book uses a lot of exercises which I found really useful as it made it easier for me to understand some of the more advanced drawing techniques. I really liked the way that the exercises are structured too. Your first start with a short explanation of what you need to do and then there are a number of easy to follow steps that take you through how to accomplish the task. Each exercise finishes with an in-depth explanation of what you just did and the techniques you used.I've used JavaScript libraries like Flot a lot in the past for data visualization so it's really interesting to learn how to create charts from scratch.Later in the book you learn about a number of JavaScript libraries that you can use for data visualisation as well as looking at some Google APIs. I particularly enjoyed the section on using Google Spreadsheets as a data source.The book does assume some prior programming experience so I wouldn't recommend it for beginners, but anyone with a modest JavaScript background should be able to work through the examples just fine.If you are a front-end developer looking to learn more about data visualization and the Canvas API I cannot recommend this book highly enough.
Amazon Verified review Amazon
Rob Delaporte Jun 22, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you have a need to know how to better utilize the canvas then this is the book for you. Although not a book for beginners it is very easy to read and follow along. Well written and a valuable addition to any html5 developers library.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.