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


There you have it; a simple way to create a HTML5 Canvas Graph for use on your projects.
I hope this helps you.



Tagged with:

View all contributions by


Related Articles


Stay connected with us

Add us on Google+

Follow us on Facebook

Follow us on Twitter

Get updates via RSS

Get email updates


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">