• .NET Developer Tools DevTools

    UI controls for ASP.NET AJAX, MVC, WPF,
    Silverlight, Windows 8 and Windows Phone

  • Hybrid Mobile Development Icenium

    Cross-platform Mobile Development Tool
    with cloud-based architecture

  • HTML5 / JavaScript Development Kendo UI

    Everything you need to build sites and
    mobile apps with JavaScript and HTML5

  • Testing Tools TestStudio

    One easy tool for Functional, Performance,
    Load and Mobile software testing

  • Web Presence Platform Sitefinity CMS

    Everything for your online business - content
    management, ecommerce, emarketing

  • Agile Project Management TeamPulse

    Simple and intuitive project management
    and collaboration software

Contact us

We are here for you.
  • usa+1‒888‒365‒2779
  • uk+44‒20‒7291‒0580
  • bg+359‒2‒8099850
  • de+49‒89‒2441642‒70
  • au+61‒2‒8090‒1465
  • emailsales@telerik.com
Your account Access to your products, updates and support
Telerik Product Families
  • Your Account
    Your Account
    Log in
  • ABOUT US

    About Telerik

    • Company
    • Press Center
    • Customers
    • Community
    • Careers
    • Contacts
Kendo UI - The way of HTML5
Products ▼
Kendo UI Web Kendo UI Mobile Kendo UI DataViz Server Side Wrappers
Demos Purchase Download
Blogs Documentation
Support ▼
Premium Forums StackOverflow Forums
Resources ▼

Featured Resource

Kendo UI Dojo


Blogs Code Library Demos Documentation FAQ Testing
Premium Forums Roadmap User Voice Videos Webinars More Resources
Contact Us Search
 

Blogs Archive

Easy Charting with JavaScript and HTML5

Friday, September 09, 2011 by Kendo UI Team Blog | Comments 7

imageOne of the coolest things that HTML5 brings to the table is technology for doing rich visualizations directly in the browser. Think about it. For years, web developers have been forced to do one of three things if they want to present a rich visual element (like a chart):

  1. Make a round-trip to the server
    The server creates or fetches the necessary image data and pipes the results back to the browser. Works everywhere, but the results are usually static. Any changes to the image require more trips to the server.
  2. Use a browser plug-in
    Plug-ins clearly work-around browser limits and can provide rich visual renderings, but they require a software install and introduce a whole new (non-standard) layer of technology that must be learned and maintained by developers.
  3. Fugly browser hacks
    You've seen them. CSS and HTML that's manipulated and abused to give the appearance of something more "image-like." This method is painful, crude, and wrong. But it's been one of the only options for years…

None of these options are ideal for the HTML/JavaScript developer. For doing something as simple as drawing a basic shape, web developers have been out-of-luck in the browser.

Until now.

HTML5 is bringing with it two technologies that give developers the ability to draw in the browser: Canvas and Scalable Vector Graphics (SVG). Both give developers a way to directly manipulate pixels in the browser, which unlocks a whole host of new possibilities for "pure" HTML and JavaScript applications. These two technologies have some key differences, though.

Canvas

Canvas is part of the HTML5 spec. It provides developers with what amounts to a writable bitmap area on a page that can be manipulated with JavaScript. In fact, you must use JavaScript to display anything on a canvas. It is not markup based, so API calls are required to draw.

The pixel-driven nature of canvas makes it ideal for scenarios where rendering speed is key, such as games. It doesn't matter if you have 1 or 10,000 "objects" being painted to your canvas, if the resolution is the same, it's all about redrawing the same pixel area.

The downside of canvas' pixel-driven nature is that it's harder to interact with. If you do have "objects" that you want users to interact with, you have create and track those objects on your own in JavaScript. And a designer can't create a "canvas" in Illustrator. API calls have to be programmed to make canvas work.

SVG

Scalable Vector Graphics have actually been around much longer than HTML5. Browsers like Firefox, Opera, and Safari have offered varying degrees of support for SVG since 2005. Why is SVG only now getting a lot of attention?

You guessed it. Internet Explorer.

One of the only browsers not to support SVG in the last 5 years was IE. And since IE was (and is) the dominant browser during this time, SVG usage was minimal. IE9 has finally added SVG support, though, and along with improved support across all other browsers, SVG is finally ready for primetime.

Unlike canvas, SVG is vector-based (not pixel-based) and is created with markup (instead of APIs). SVG elements, when rendered, actually become part of the page DOM, which means they have properties, events, and are much easier to use for illustrations that expect user interaction. And since SVG is markup-based, designs can be easily exported to SVG format from Illustrator, loaded by the browser, and even cached like images.

The downside to living in the DOM is memory. Highly complex visualizations (thousands of objects) will strain browsers since every element in the SVG image is an object (with its own memory needs). That makes SVG great for things like data visualization or logos, leaving complex visual rendering to canvas.

Older Browsers?

Clearly, adopting canvas and SVG for rich, interactive visualizations in HTML is a no-brainer, but what happens for older browsers, especially IE (which, as we said, lacks any SVG support pre-IE9)? Fortunately, there is a very similar technology to SVG baked-in to IE5 through IE9 called Vector Markup Language (VML).

Originally created for Microsoft Office, VML has a lot of overlap with SVG. When used in conjunction with SVG, VML gives us a way to reach most actively used browsers with some type of in-browser rendering.

Kendo UI Charts

Now that you fully understand the "drawing" technologies of HTML5, let's look at how Kendo UI Charts make it easy for you to add rich data visualizations to any HTML site or app.

Kendo UI charting uses two technologies to automatically provide broad browser support: SVG and VML. You don't have to worry about older versions of IE. Kendo UI Charts will provide the proper rendering without requiring any extra code.

Why not canvas? Three reasons:

  1. SVG is interactive. This makes it easy for us to add features like the dynamic tooltips (and even more interactivity to come)
  2. SVG/VML is more broadly supported. Unlike canvas, which is an HTML5 feature, SVG/VML help us support a broad range of new and older browsers without resorting to polyfills.
  3. SVG is vector based. And charts are relatively simple data visualizations. Using SVG lets charts scale crisply to any display size (big or small), and avoids wasting memory rendering more pixels on larger screens.

Getting Started with Kendo UI Charts

Using Kendo UI charts to do data visualization couldn't be simpler. All you need is some data (JSON, JavaScript array, whatever) and a few lines of JavaScript.

To setup a chart, we need to define where in the HTML we want it rendered using a simple DIV tag, like this:

<div id="chart"></div>

 

And then we need to initialize the Kendo UI Chart using the simple API. For this basic example, I'll give the chart a title, define 2 series of local data (one defined in the Chart config, one an external JavaScript array), and define my axis.

//External local array
var rtData = [3,15,30,45,92];

$(function(){
  $("#chart").kendoChart({
    title:{ text:"@toddanglin Stats" },
    series:[
      {
        name:"Followers",
        data:[89,212,450,680,1140],
        stack:true
      },
      {
        name:"RTs",
        data: rtData
      }
    ],
    categoryAxis:{
      categories:["February","March","April","May","June"]
    }
  });
});

 

Which produces the following data visualization:

image

This isn't an image. (Well, this is, in the blog post, but you know what I mean.) This is SVG drawn directly in the browser with JavaScript. This works in modern browsers. This works in older versions of IE (thanks to Kendo UI Chart's auto-VML). This works on phones, tablets, and devices.In fact, you can give this chart a spin with this live JSBin.

With the rendering happening the browser, this opens the door to:

  • Visualizing rapidly updating data
  • Animating the chart
  • Creating interactive charts
  • Hiding/Showing series without extra calls to the server

As the Kendo UI Chart evolves in the current beta, it will add many of these features, like interactive charts, giving you even more power through a simple API.

Chart Types

In today's beta, Kendo UI Chart support three chart types: Line, Bar, and Column. Going forward, Kendo UI Chart will add support for many additional chart types, including Pie, Scatter, and more. As more chart types are added, the simple API will make it easy to switch chart types, so you just keep getting more power.

In fact, even in the current beta, you can mix chart types. For example, I can edit the previous example to make one series a column chart (vertical bars), and the other series a line chart:

series:[
  {
    name:"Followers",
    data:[89,212,450,680,1140],
    stack:true
  },
  {
    name:"RTs",
    data: rtData,
    type:"line"
  }
]

Producing this mixed chart:

image

 

Rapidly Changing Data

To wrap-up this brief introduction to the Kendo UI Chart, let's take advantage of our new found ability to draw charts in the browser and configure Kendo UI Chart to redraw with new data 10 times a second. Unfortunately, the current Kendo UI Chart beta doesn't yet have an API that let's us do a 1-step animated refresh of the chart, but we can easily handle this scenario by simply recreating the chart each time our data changes.

You can see the live effect by visiting this updated JSBin example, but here is the relevant snippet of JavaScript:

createChart: function(){
  this.updateCount += 1;
  
  //Recreate the chart with each update
  this.chartElement.kendoChart({
    title:{ text:"CPU Stats" },
    dataSource:{
      data: this.getRandomSeriesData() //Random chart data
    },
    series:[
      {
        name:"Stats",
        field:"value"
      }
    ],
    categoryAxis:{
      field:"type"
    }
  });  
  
  //Redraw the chart 50 times in 100ms intervals
  if(this.updateCount < 50){
    setTimeout(function(){app.createChart();},100);
  }else{
    alert("Done updating."); 
  }
}

This code clearly has a few external dependencies (which you'll find in the complete JSBin example), but the concept is simple. Using a JavaScript timeout executing in 100ms cycles, recreate the chart with new random data. Each time this happens, the chart SVG (or VML) will rapidly redraw in the browser.

In a real-world implementation, you'd more likely redraw the chart as the result of getting new data from the server or changing user input. But this example serves to illustrate that with Kendo UI Charts drawing in the browser, you can do some cool things with data visualization that don't require the help of a server or browser plug-in.

Enjoy! And stay tuned for even more info on things you can do with HTML5, JavaScript, and Kendo UI.

Download the Kendo UI Beta today!

About the Author
Todd Anglin is an avid HTML5, CSS3, and JavaScript advocate, and geek about all things web development. He is an active speaker and author, helping developers around the world learn and adopt HTML5. Todd works for Telerik as Chief Evangelist where his current technical focus in on Kendo UI. Todd is @toddanglin on Twitter.

7 Comments

  1. 1 Steve 10 Sep 2011
    Im pretty sure this is the first time "fugly" has been used in a telerik blog post, and I love it :)
  2. 2 Milind 30 Sep 2011
    I'd like to know can we use the features of javascript combined with HTML5 since , some features like email local validation, doesn't provide satisfactory output as it must, using HTML5's email input type. so can we do it?
    thank you.
  3. 3 Manjeet 07 Nov 2011
    Hi I am working with HCL technologies and have some problem in HTML5 plz look in it and if possible plz write me the correct solution manjeet.chandhok@gmail.com

     am using following code to convert my image into grey scale, on local machine it is fine but when I deploy the same on server it passes Uncaught Error: INDEX_SIZE_ERR: DOM Exception 1 I wonder is it due to different domain, I am not sure but problem is due to "getImageData". Also, this problem is only on chrome.

    I have read lot of posts and tried a lot, but seems like nothing working for me.

    Thanks in Advance...

    function grayscale(img) {
             
    var canvas = document.createElement('canvas');
             
    var ctx = canvas.getContext('2d');
             
    var imgObj = new Image();
             imgObj
    .src = img;
             canvas
    .width = imgObj.width;
             canvas
    .height = imgObj.height;
             ctx
    .drawImage(imgObj, 0, 0);
             
    var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
             
    for (var y = 0; y < imgPixels.height; y++) {
             
    for (var x = 0; x < imgPixels.width; x++) {
             
    var i = (y * 4) * imgPixels.width + x * 4;
             
    var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                        imgPixels
    .data[i] = avg;
                        imgPixels
    .data[i + 1] = avg;
                        imgPixels
    .data[i + 2] = avg;
                   
    }
               
    }
                ctx
    .putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
               
    return canvas.toDataURL();
           
    }
  4. 4 Manjeet 07 Nov 2011
    Hi I am working with HCL technologies and have some problem in HTML5 plz look in it and if possible plz write me the correct solution manjeet.chandhok@gmail.com

     am using following code to convert my image into grey scale, on local machine it is fine but when I deploy the same on server it passes Uncaught Error: INDEX_SIZE_ERR: DOM Exception 1 I wonder is it due to different domain, I am not sure but problem is due to "getImageData". Also, this problem is only on chrome.

    I have read lot of posts and tried a lot, but seems like nothing working for me.

    Thanks in Advance...

    function grayscale(img) {
             
    var canvas = document.createElement('canvas');
             
    var ctx = canvas.getContext('2d');
             
    var imgObj = new Image();
             imgObj
    .src = img;
             canvas
    .width = imgObj.width;
             canvas
    .height = imgObj.height;
             ctx
    .drawImage(imgObj, 0, 0);
             
    var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
             
    for (var y = 0; y < imgPixels.height; y++) {
             
    for (var x = 0; x < imgPixels.width; x++) {
             
    var i = (y * 4) * imgPixels.width + x * 4;
             
    var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                        imgPixels
    .data[i] = avg;
                        imgPixels
    .data[i + 1] = avg;
                        imgPixels
    .data[i + 2] = avg;
                   
    }
               
    }
                ctx
    .putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
               
    return canvas.toDataURL();
           
    }
  5. 5 Christophe 14 Nov 2011
    I just discovered Kendo UI. I am reading through your blog posts and find them very informative. I used canvas charts in the past and was looking for an svg alternative, it seems that I've come to the right place. Thanks!
  6. 6 Leonid Mal 24 Sep 2012
       @(Html.Kendo().Chart()
              .Name("Chart")
    ...

     

    How refresh  Chart

  7. 7 Vitaly 28 Nov 2012
    Hi.
    When I see demos http://demos.kendoui.com/dataviz/pie-charts/index.html, and double click on chart, error is occured in browser debuger:
    Error in event handler for 'undefined': INDEX_SIZE_ERR: DOM Exception 1 Error: Index or size was negative, or greater than the allowed value. at J (chrome-extension://mgijmajocgfcbeboacabfgobmjgjcoja/content_js_min.js:14:142) at null.<anonymous> (chrome-extension://mgijmajocgfcbeboacabfgobmjgjcoja/content_js_min.js:17:184) at chrome-extension://mgijmajocgfcbeboacabfgobmjgjcoja/content_js_min.js:1:182 at miscellaneous_bindings:286:9 at chrome.Event.dispatchToListener (event_bindings:387:21) at chrome.Event.dispatch_ (event_bindings:373:27) at chrome.Event.dispatch (event_bindings:393:17) at Object.chromeHidden.Port.dispatchOnMessage (miscellaneous_bindings:253:22)

Comment

  1. Click to add

  2. Click to add

  3. Click to add

  4.    
     
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
     
      
       
Blogs feed
Categories

  • Tutorials (26)
  • Release (33)
  • Browsers (7)
  • Extensions (3)
  • Tip of the Week (10)
  • Videos (5)
  • Concepts and Theory (13)
  • Misc. (25)
  • Framework Constructs (6)
  • Mobile (6)
  • UI Widgets (5)
  • Blogs (1)
Archive
  • 2013 May (6)
  • 2013 April (10)
  • 2013 March (9)
  • 2013 February (12)
  • 2013 January (10)
  • 2012 December (9)
  • 2012 November (11)
  • 2012 October (6)
  • 2012 September (7)
  • 2012 August (8)
  • 2012 July (10)
  • 2012 June (8)
  • 2012 May (10)
  • 2012 April (7)
  • 2012 March (13)
  • 2012 February (10)
  • 2012 January (6)
  • 2011 December (10)
  • 2011 November (4)
  • 2011 October (6)
  • 2011 September (5)
  • 2011 August (9)
Home Web Mobile DataViz Server Wrappers Whitepapers Surveys Chrome Icenium Contact Us

Kendo UI framework is developed by Telerik - a leading provider of UI components for web, desktop and mobile applications. Trusted by over 100,000 customers worldwide for our devotion to quality and industry-best technical support, Telerik helps professionals maximize their productivity and "deliver more than expected" every day.

kendoui - powered by html5, css3 & jquery
get social
  • Twitter
  • Facebook
  • Google plus
  • RSS
Privacy Policy | Branding Guidelines
Powered by Sitefinity CMS

Copyright © 2011 - 2013 Telerik Inc. All rights reserved.