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 a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781849693707
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Nov 23, 2012
Length: 344 pages
Edition : 1st
Language : English
ISBN-13 : 9781849693707
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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.