饼图画布不在IE中工作(已编辑)

时间:2013-03-07 09:20:09

标签: javascript html5-canvas excanvas

我是html5和javascript的新手。

第一次尝试创建html5,javascript,css3饼图**(不使用jquery)**。饼图可以在chrome和firefox中完美创建。然后过了一会儿,我不小心在Internet Explorer(IE)中打开了index.html,饼图丢失了。后来我意识到即使是Komodo的浏览器也没有显示饼图。

尝试

1)google,看到了一个叫做excanvas.js的东西。

2)在index.html中包含此行

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

3)在pie_chart_simple.js initialize_para()函数中包含这一行,

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

结果:

仍然无法在Internet Explorer中查看饼图。 (仅显示表值)

不确定度: 1)使用excanvas.js? (因为不使用jquery而放置代码的位置) 2)通过ie?

解码的颜色格式

介意帮忙吗?谢谢。

有两个文件:

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

1 个答案:

答案 0 :(得分:2)

每个浏览器版本都不支持

画布(支持:IE 9 +,FF 3.5 +,Chrome 4.0 +,Safari 4.0 +,Opera 10.5 +)。

excanvas只为早期的IE版本带来了特定的画布功能子集。

对于IE 9中的画布支持,您需要使用正确的doctype <!DOCTYPE html>,以便IE不处于兼容模式。

修改 我做了一些测试,似乎取决于<meta http-equiv="X-UA-Compatible"doctype的设置,至少32位版本的IE 9强制加载在iframe中的文档具有与父文件。但我不知道为什么在64位版本中这种行为有所不同。

所以在这里的所有PC上(Windows 7 64位/ 32位和windows vista),32位版本的IE 9都不会在jsfiddle的iframe中显示饼图。但是如果直接打开预览面板(http://fiddle.jshell.net/torresho/wmJb6/6/show/),它就可以在所有面板中使用。