HTML5 Canvas Graph


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 <canvas> 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 <canvas> 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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s