• No results found

inserting a CanVaS-driven dynamic Chart

In document HTML5 Web Designer (Page 156-161)

The second image-generation tool you can use in HTML5 is CANVAS. The following project will add a dynamically drawn bar chart to your page. The advantages of using dynamic images, such as CANVAS, are that you can programmatically dictate the result.

For instance, the chart you will be drawing illustrates growth for the last four quarters and the projected growth for the next quarter.

You can easily update the chart as your data are going to be driven from a JavaScript array. There is no need to get out Photoshop and update a JPEG image of the bar chart. You can update the code in the web page and you are good to go.

Okay, so let’s get started. You are going to need to download the files from www.visualizingtheweb.com.

1. Open the file named “news.html.” You are going to add the bar chart. Add the following CANVAS tag to that section to give the chart a place on your page.

<article id=“article_two” style=“position: absolute; left:

420px; top: 350px; width: 315px; height: 195px; z-index: 2”>

<h1>What we do</h1>

<p><time datetime=”2010-03-15T10:32:17”>March 15, 2010</time></p>

<H2>2010 Annual Report</H2>

<video controls><source src=‘2010 Report.ogv’></video>

<canvas id=“barChart” width=“600” height=“400”>

</canvas>

</article>

2. It is important to notice that the CANVAS element has an ID labeled barChart. The barChart ID will be used to link the JavaScript definition to the CANVAS element. Begin by adding a new JavaScript element to the page. Place the new JavaScript element inside of the HEAD element.

<script type=“text/javascript”>

3. The next step is to create a new function that defines the CANVAS element.

function graph() {

var graphCanvas = document.getElementById(‘barChart’);

4. Ensure that the element is available within the DOM.

if (graphCanvas && graphCanvas.getContext) {

5. Open a two-dimensional context within the canvas.

var context = graphCanvas.getContext(‘2d’);

6. Draw the bar chart.

drawBarChart(context, data, 50, 100, (graphCanvas.

height - 20), 50);}

204

Project 4: creating SVg LogoS and canVaS chartS

7. The following array contains the data you will use to populate the final bar chart.

var data = new Array(5);

data[0] = “First Quarter,200”;

data[1] = “Second Quarter,120”;

data[2] = “Third Quarter,80”;

data[3] = “Fourth Quarter,330”;

data[4] = “Projected Growth,345”;}

8. The line of code draws the bar chart with the specified width, height, and starting position.

function drawBarChart(context, data, startX, barWidth, chartHeight, markDataIncrementsIn) {

9. The following draws the X and Y axes onto your chart.

context.lineWidth = “1.0”;

var startY = 380;

drawLine(context, startX, startY, startX, 30);

drawLine(context, startX, startY, 570, startY);

context.lineWidth = "0.0”;

var maxValue = 0;

for (var i=0; i<data.length; i++) {

10. The following will extract the data from the array.

var values = data[i].split(“,”);

var name = values[0];

var height = parseInt(values[1]);

if (parseInt(height) > parseInt(maxValue)) maxValue = height;

11. The date is now written to the chart.

context.fillStyle = “gray”;

drawRectangle(context, startX + (i * barWidth) + i, (chartHeight - height), barWidth, height, true);

12. The following will add the column markers on the left side of the chart.

context.textAlign = “left”;

context.fillStyle = “#000”;

context.fillText(name, startX + (i * barWidth) + i, chartHeight + 10, 200);}

13. Data markers are added to the Y axis.

var numMarkers = Math.ceil(maxValue/

markDataIncrementsIn);

context.textAlign = “right”;

context.fillStyle = “#000”;

var markerValue = 0;

for (var i=0; i<numMarkers; i++) {

context.fillText(markerValue, (startX - 5), (chartHeight - markerValue), 50);

markerValue += markDataIncrementsIn;

}}

14. The following JavaScript will draw a line on the context start and end points.

function drawLine(contextO, startx, starty, endx, endy) {

contextO.beginPath();

contextO.moveTo(startx, starty);

contextO.lineTo(endx, endy);

contextO.closePath();

contextO.stroke();}

15. The following draws a rectangle around the charts.

function drawRectangle(contextO, x, y, w, h, fill) { contextO.beginPath();

contextO.rect(x, y, w, h);

contextO.closePath();

contextO.stroke();

if (fill) contextO.fill();

}

</script>

16. An onLoad event is needed in the BODY element to load the CANVAS JavaScript into the page.

<body onLoad=“graph();”>

17. Save your document and view your CANVAS-driven chart (Figure 4.5Proj). Try changing the data values in the array.

You will see that the chart updates automatically.

Figure 4.5Proj the canVaS element is used to create the bar chart without needing a traditional image format such as jPeg or Png.

206

Project 4: creating SVg LogoS and canVaS chartS

Summary

SVG and CANVAS are technologies that have been a long time coming for HTML. Using scripting languages, such as XML and JavaScript, you can now programmatically create the illustrations you want on your page. You are not limited to the forced restrictions a traditional pixel-based image, such as JPEG, places on you.

In this project you have successfully added an SVG image to your web site. In addition, you have seen how you can create your own SVG illustrations using online cloud services such as Google Docs. You also created a bar chart constructed using the CANVAS object. In the next section of the book you are going to build onto your knowledge of JavaScript and add complex interactivity with Ajax libraries.

HTML5. doi: 10.1016/B978-0-240-81328-8.00010-0

© 2010 Elsevier Inc. All rights reserved.

209

CSS, SVG, and Video are all great improvements to HTML5. The role for HTML5, however, is not to simply add eye-candy, but to enable developers to create applications in web browsers that are equal in performance to desktop applications. To accom-plish this, you need a powerful development language that gives developers the ability to create sophisticated solutions. The answer to this is JavaScript, the world’s most popular program-ming language.

Currently, the belief is that web applications simply are not as powerful as desktop applications. The reason for this is not due to JavaScript, but the engines inside of your web browser that process JavaScript. The faster a script can be processed, the more sophisticated your applications can become.

During 2009, web browser companies played a game of leap frog trying to reset speed benchmarks. FireFox, Safari, Google, and Opera played constantly. Toward the end of the year it appeared that the only company that would be left in the dark was Microsoft with the Internet Explorer 8 browser. At the fall 2009 PDC presentation Microsoft showed off an early devel-oper version of IE9 running standard JavaScript tests (such as the SunSpider test at http://www2.webkit.org/perf/sunspider-0.9/

sunspider.html) that placed its JavaScript engine on par with its competitors (see Figure 5.1).

The goal of this article is to review JavaScript, including how it is used in HTML5, how you can build upon the work of others through Ajax, and how to implement popular Ajax libraries into your work.

210

HTML5 JavaScripT ModeL

In document HTML5 Web Designer (Page 156-161)