Question

I'm new to html5 and javascript.

Trying to create a html5, javascript, css3 pie chart **(not using jquery)**for the first time. The pie chart can be perfectly created in chrome and firefox. Then after a while, i accidentally opened the index.html in Internet Explorer(IE), the pie chart is missing. Later on i realize even the browser in Komodo does not display the pie chart.

Tried

1)google, and saw something called excanvas.js.

2)include this line in index.html

<!-- can't post script with arrow bracket in stackoverflow, uncomment & replace < with |-->
<!-- |script src="./js/excanvas.js"||/script|-->

3)include this line in pie_chart_simple.js initialize_para() function,

if(typeof canvas.getContext==='undefined')return;

Result:

Still can't view the pie chart in Internet explorer. (only the table values are displayed)

Uncertainty: 1) The use of excanvas.js? (The position to place the code since not using jquery) 2) the color format decoded by ie?

Mind to help? Thank you.

There are 2 files:

1)index.html:

2)pie_chart_simple.js

(jsfiddle link: http://jsfiddle.net/torresho/wmJb6/6/)

1) index.html

<!DOCTYPE html>
<html>
<head>
<title>Pie Chart</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- can't post script with arrow bracket in stackoverflow, uncomment & replace < with |-->
<!-- |script src="./js/excanvas.js"||/script|-->
<!-- |script type="text/javascript" src="./js/pie_chart_simple.js"||/script| -->
</head>
<body>

<div id="container">

  <canvas id="chart" width="380" height="460"></canvas>

  <table id="chartData">

    <tr> 
      <th>Club</th><th>Points</th>
     </tr>

    <tr style="color: #0DA068">
      <td>MU</td><td>71</td>
    </tr>

    <tr style="color: #194E9C">
      <td>MC</td><td>59</td>
    </tr>

    <tr style="color: #ED9C13">
      <td>Tot</td><td>54</td>
    </tr>

    <tr style="color: #ED5713">
      <td>Chel</td><td>52</td>
    </tr>

    <tr style="color: #057249">
      <td>Ars</td><td>52</td>
    </tr>

  </table>

</div>

</body>

</html>

2) pie_chart_simple.js:

// jquery method // Run the code when the DOM is ready
//$( pie_chart_simple ); 

window.onload=function(){
  pie_chart_simple();
}


function pie_chart_simple() {

  // Pie Chart Configuration Settings
  var chartSizePercent = 55;                        // The chart radius relative to the canvas width/height (in percent)
  var chartStartAngle = -0.5 * Math.PI;             // Start the chart at 12 o'clock instead of 3 o'clock
  var sliceGradientColour = "#ddd";                 // Colour to use for one end of the chart gradient (#ddd = RGB(211,211,211) = light grey)

  // Variables for the chart
  var canvas;                                       // The canvas element in the page
  var canvasWidth;                                  // Width of the canvas, in pixels
  var canvasHeight;                                 // Height of the canvas, in pixels
  var centreX;                                      // X-coordinate of centre of the canvas/chart
  var centreY;                                      // Y-coordinate of centre of the canvas/chart
  var chartRadius;                                  // Radius of the pie chart, in pixels

  var table;                                        // The table element in the page
  var numRows;                                      // The number of rows in the table
  var label_array = [];                             // An array to store the first column values (labels)
  var value_array = [];                             // An array to store the 2nd column values (values)
  var chartColors = [];                             // Chart colors (pulled from the HTML table)
  var totalValue = 0;                               // Total of all the values in the chart

  var startAngle = [];                               // Start angle of each slice 
  var endAngle = [];                                // End angle of each slice
  var startX =0;
  var startY =0;
  var change_color=0;
  initialize_para();

  /********************************** Initialization - starto************************************************/
  function initialize_para() {
      // Define the canvas element
      canvas = document.getElementById('chart');

      console.log(canvas);
      console.log('canvas='+canvas);
      console.log(canvas.getContext);
      console.log(typeof canvas.getContext);
      console.log(typeof canvas.getContext==='undefined');
      // Check if the browser does not support canvas (e.g. ie)
      // code goes here... 
      // Exit if the browser isn't canvas-capable
      if ( typeof canvas.getContext === 'undefined' ) return;


      // Acquire the parameters to determine the chart size
      canvasWidth = canvas.width;
      canvasHeight = canvas.height;
      centreX = canvasWidth/2;
      centreY = canvasHeight/2;
      chartRadius = (Math.min(canvasWidth,canvasHeight)/2)*(chartSizePercent/100);
        //alert('canvasWidth='+canvasWidth+', canvasHeight='+canvasHeight+' ,chartRadius='+chartRadius); //popup
        console.log('canvasWidth='+canvasWidth+', canvasHeight='+canvasHeight+' ,chartRadius='+chartRadius); //log

      // Get the pie chart data - labels, values and color (from the html table)
      // Alternatively, can be simplified using each() in jquery
      table = document.getElementById('chartData');
      numRows = table.rows.length;

      for (var i = 1; i<numRows; i++) {
        var trs = table.getElementsByTagName('tr')[i];
        label_array[i-1] = trs.cells[0].innerText;                // label
        value_array[i-1] = trs.cells[1].innerText;                // value
        chartColors[i-1] = trs.style.color;                       // color
        totalValue += parseFloat(value_array[i-1]);               // total value
            console.log(label_array[i-1]+' '+value_array[i-1]+' '+chartColors[i-1]+' '+totalValue);
                  // MU 71 rgb(13, 160, 104) 71 
                  // MC 59 rgb(25, 78, 156) 130 
                  // Tot 54 rgb(237, 156, 19) 184
                  // Chel 52 rgb(237, 87, 19) 236
                  // Ars 52 rgb(5, 114, 73) 288 
      }

      // Compute and store the start and end angles of each slice of the data

      var currentPos = 0;       //The current position of the slice in the pie(from 0 to 1)

        //    (3/2)pi radians / -ve pi/2 radians
        //                ^
        //                |<
        //                |  )   (starting point is here ccw direction, when drawing in canvas)
        //1pi radians-----|----> 0pi radians / 2pi radians
        //                |
        //                |
        //            pi/2 radians

      for (var i = 0; i<numRows-1; i++) {
        //console.log(i+'    '+2*currentPos+'PI');
        startAngle[i] = 2*Math.PI*currentPos;
        endAngle[i] = 2*Math.PI*(currentPos+(value_array[i]/totalValue));
        currentPos += value_array[i]/totalValue;
          console.log(i+'    '+'Slice'+' '+(i+1)+'  StartAngle: '+startAngle[i]+'   EndAngle: '+endAngle[i]);
                // 0    Slice 1  StartAngle: 0   EndAngle: 1.5489797111449675 pie_chart_simple.js:80
                // 1    Slice 2  StartAngle: 1.5489797111449675   EndAngle: 2.8361600344907854 pie_chart_simple.js:80
                // 2    Slice 3  StartAngle: 2.8361600344907854   EndAngle: 4.014257279586958 pie_chart_simple.js:80
                // 3    Slice 4  StartAngle: 4.014257279586958   EndAngle: 5.148721293383272 pie_chart_simple.js:80
                // 4    Slice 5  StartAngle: 5.148721293383272   EndAngle: 6.283185307179586 
      }

      // After working out all the data needed for the chart, draw the chart
    drawChart();

    //$('#chart').click ( handleChartClick ); // jQuery way
    // element.onclick = functionRef;
    //canvas.onclick = handleChartClick;

  }
  /********************************** Initialization - endo************************************************/

  /********************************** Draw chart - starto************************************************/

  function drawChart() {

    // Get the drawing context (canvas tag is use to draw graphics on the fly)
    // getContext() method returns an object that provides methods and properties for drawing on the canvas
    var context = canvas.getContext('2d');

    // Clear the canvas, ready for the new frame
    // (x-coordinate of upper-left corner, y-coordinate of upper-left corner,
    // width of the rectangle to clear (in pixles), height of the rectangle to clear (in pixels))
    context.clearRect(0,0,canvasWidth,canvasHeight);

    // Draw an individual slice in the chart iteratively to form a complete circular pie chart
    for (slice_number=0; slice_number<numRows-1; slice_number++) {
      drawSlice(context,slice_number);
    }
  } //function drawChart() ends

  function drawSlice(context,slice_number) {
    // Compute the adjusted start and end angles for the slice (start at 12 o'clock instead of 3 o'clock)
    var startAngle_offset = startAngle[slice_number] + chartStartAngle;
    var endAngle_offset = endAngle[slice_number] + chartStartAngle;

    // Draw the pie from the centre
    startX = centreX;
    startY = centreY;

    // Set the gradient fill for the slice
    var sliceGradient = context.createLinearGradient(0,0,canvasWidth*0.75,canvasHeight*0.75);
    sliceGradient.addColorStop(0, sliceGradientColour);
    sliceGradient.addColorStop(1, chartColors[slice_number]);
    //liceGradient.addColorStop(1,'#fff');
    //???????????
    //sliceGradient.addColorStop(0,"black");
    //sliceGradient.addColorStop(1,"white");

      //console.log('startAngle_offset='+startAngle_offset+', endAngle_offset='+endAngle_offset); //log
      //console.log('startX='+startX+', startY='+startY); //log
      //console.log('sliceGradient='+sliceGradient+', sliceGradient.addColorStop(0, sliceGradientColour)='+sliceGradient.addColorStop(0, sliceGradientColour)); //log
      //console.log('sliceGradient.addColorStop(1)='+sliceGradient.addColorStop(1,'#fff')+', sliceGradientColour='+sliceGradientColour); //log
      //console.log('chartColors[slice_number]='+chartColors[slice_number]+', slice_number='+slice_number); //log
      //console.log(' -----');

    // Draw the slice
    context.beginPath();                          
    context.moveTo(startX,startY);
    context.arc(startX,startY,chartRadius,startAngle_offset,endAngle_offset,false); //last field optional. Specifies whether the drawing should be counterclockwise or clockwise. False=clockwise, true=counter-clockwise
    context.lineTo(startX,startY);
    context.closePath();
    if (change_color == 1) {
      context.fillStyle = "rgba(0,0,0,0)";
    }
    else{
    context.fillStyle = sliceGradient;}
    context.fill();
    context.shadowColor = "rgba(0,0,0,0)";

    // Draw the slice border
    context.stroke();

    // add label
    context.fillText(label_array[slice_number],startX+slice_number*10+100,startY+slice_number*10+100);
    context.fillText(value_array[slice_number],startX+slice_number*10+100,startY+slice_number*10+100+20);
  }

 /********************************** Draw chart - endo ************************************************/

} // function pie_chart_simple() ends
Was it helpful?

Solution

canvas is not supported in every browser version (it is supported by: IE 9+, FF 3.5+, chrome 4.0+, safari 4.0+, opera 10.5+).

excanvas only brings a certain subset of the canvas features to earlier IE versions.

for canvas support in IE 9 you need to use the correct doctype <!DOCTYPE html> so that IE is not in compatibility mode.

EDIT i did some tests and it seems that depending on the settings of <meta http-equiv="X-UA-Compatible" and the doctype, at least the 32-bit version of IE 9 forces the document loaded in the iframe to have the same mode as the parent document. but i don't know why this behaves differently in the 64-bit version.

So on all PCs here (windows 7 64-bit/32-bit and windows vista) the 32-bit version of IE 9 does not display the pie chart in the iframe of jsfiddle. But if opening the preview panel (http://fiddle.jshell.net/torresho/wmJb6/6/show/) directly it works in all of them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top