Tuesday 20 May 2014

HTML5 Canvas Graph

IMG

Create an HTML5 canvas graph with javascript.

Today we will be creating a graph that looks similar to the Google Analytics Graph using HTML5 Canvas and Javascript to draw the graph. HTML5 Graph has many uses including website statistics, pageviews, visits, and so on. We will cover the basics of creating a simple graph.

The Markup


We need to trigger the NewGraph() function when the document loads. To achieve this we will be using the onLoad event.

 

 

We use the  element to draw the image to.

 

 

The whole HTML5 markup below:

 

The Javascript


Now for the javascript. The NewGraph() function will be called when the page loads. We start the JS with our function named NewGraph().

 

 

First, find the  element with the id of graph. Then, call its getContext() method (you must pass the string “2d” to the getContext() method). The getContext(“2d”) object is a built-in HTML5 object.

 

 

We will store the line values in an array() for the x and y values on canvas.

 

 

Create an Image object.

 

 

Before you can draw the image, the image must be fully loaded. To determine if an image is fully loaded, we use the onload event.

 

 

Start display of the image from top left of the canvas, x set to 0 and y set to 0 as well.

 

 

Line stroke width.

 

 

Line joint shape.

 

 

Line stroke color.

 

 

Use the beginPath() to start drawing a new path.

 

 

We use the JSON.parse() method to parse a string as JSON.

 

 

Draw lines from the array loop.

 

 

Fill the stroke.

 

 

Line joint color.

 

 

Draw circles from array loop.

 

 

Load the image into memory.

 

The whole Javascript

No comments:

Post a Comment