我们到底能走多远系列(34)

扯淡:

  送给各位一段话:

    人生是一个不断做加法的过程

    从赤条条无牵无挂的来
    到学会荣辱羞耻 礼仪规范
    再到赚取世间的名声 财富 地位
    但是人生还要学会做减法
    财富名声这些身外之物有一天会失去
    朋友 亲人终有一天会离你而去
    我们自己会衰老 迟钝
    最后赤条条的离开这个世界
    我们都不太擅长做人生的减法
    很难学会放下
    放不下面子 所以要打肿脸充胖子
    放不下逝去的情感 就会沉溺其中 痛苦不堪
    放不下输赢 所以总是如履薄冰 心惊胆战
    佛说 我执 是痛苦的根源
    人生要学会 断 舍 离
    断绝不需要的东西
    舍弃多余的废物
    脱离对物品的执念
    所以想幸福 请先放下
 
 
主题:
 
  最近想用html5来话图表,就接触了下,发现html5 是一个总称而已,进去后里面分成各种标签比如:HTML5 Video,HTML5 Audio,HTML5 Canvas等等,各不相关,所以学习起来也不复杂,比如我想画图表就先学习下Canvas就好了。
  
  所以,我感觉这东西也就是调下api,没什么太大的难度,难得地方是要实现一个东西还需要学习css,javascript这些东西才行。
  
  自己画的线图: 用一个function包起来,是为了简单的封装一下内部的变量。
  
  需要注意的是代码依赖jquery。
  
  这是一个比较初步的实现,对于canvas上画图,其实直接理解成现实中那笔在话就可以了,像下面的线图,先画好x y 轴,然后再话线,再来画事件现实文字。画面变化的产生目前我发现的是用clearRect方法先清空画面,然后重画....
 
  1. function lineChart(data){
  2. var xPadding = 60;//x轴离边框的距离
  3. var yPadding = 50;//y轴离边框的距离
  4. var canvasWidth;
  5. var canvasHeight;
  6. var xAxisLength; //x轴长度
  7. var yAxisLength; //y轴长度
  8. var xTextColour = "#000000"; // x轴字体颜色
  9. var yTextColour = "#000000"; // y轴字体颜色
  10. var dotsColour = "#183487"; // 图标点的颜色
  11. var lineWidth = 2 //线宽度
  12. var lineColour = "#194E9C"; // 线颜色
  13. var lineShadowColour = "rgba( 0, 0, 0, .5 )"; // 线阴影颜色
  14. var lineShadowBlur = 15;
  15. var lineShadowOffsetX = 3;
  16. var lineShadowOffsetY = 3;
  17. var xyColour = "#4B0082"; //xy轴颜色
  18. var xToTextlength = 20; //x轴和文字的间距
  19. var yToTextlength = 10; //y轴和文字的间距
  20. var yTextNum = 6; //y轴和文字数量
  21. var chartLineFont = "bold 16px 'Trebuchet MS', Verdana, sans-serif";// xy轴字体
  22. var chooseDotTextFont = "bold 16px 'Trebuchet MS', Verdana, sans-serif";//显示提示字体
  23. var dotsToDotsXLength; //x轴间距
  24. var dotsXArray = [];
  25. var divideXArray = []; //分割每个点的竖切线的x坐标
  26. var lineChart; // The canvas element in the page
  27. init(data);
  28.  
  29. function init(data){
  30. lineChart = document.getElementById('lineChart');
  31. // Initialise some properties of the canvas and chart
  32. canvasWidth = lineChart.width;
  33. canvasHeight = lineChart.height;
  34. xAxisLength = canvasWidth - 2*xPadding;
  35. yAxisLength = canvasHeight - 2*yPadding;
  36. dotsToDotsXLength = xAxisLength / data.length;
  37. drawLineChart();
  38. // 添加事件
  39. $('#lineChart').mousemove(handleDotsMousemoveEvent);
  40. }
  41.  
  42. function drawLineChart(index){
  43. var c = lineChart.getContext('2d');
  44. // Clear the canvas, ready for the new frame
  45. c.clearRect ( 0, 0, canvasWidth, canvasHeight );
  46.  
  47. c.lineWidth = lineWidth;
  48. c.strokeStyle = xyColour;
  49.  
  50. // Draw the axises
  51. c.beginPath();
  52. c.moveTo(xPadding, yPadding);
  53. // y轴
  54. c.lineTo(xPadding, lineChart.height - yPadding);
  55. // x轴
  56. c.lineTo(lineChart.width - yPadding, lineChart.height - yPadding);
  57. c.stroke();
  58.  
  59. // Draw the the background line
  60. c.beginPath();
  61. c.strokeStyle = '#D9D6D6';
  62. for(var i = 0; i <= getMaxYPoint(getMaxY()); i += getYSpace()) {
  63. if(i != 0){
  64. c.moveTo(xPadding + 2, getYPixel(i));
  65. c.lineTo(xPadding + xAxisLength + 2, getYPixel(i));
  66. }
  67. }
  68. c.stroke();
  69.  
  70. // Draw the X value texts
  71. c.font = chartLineFont;
  72. c.fillStyle = xTextColour;
  73. c.textAlign = "center";
  74. var step = parseInt(data.length/yTextNum);
  75. for(var i = 0; i < data.length; i =i + step) {
  76. c.fillText(data[i].X, getXPixel(i), lineChart.height - yPadding + xToTextlength);
  77. }
  78.  
  79. // Draw the Y value texts
  80. c.textAlign = "right";
  81. c.textBaseline = "middle";
  82. c.fillStyle = yTextColour;
  83. for(var i = 0; i <= getMaxYPoint(getMaxY()); i += getYSpace()) {
  84. c.fillText(formatNum(i), xPadding - yToTextlength, getYPixel(i));
  85. }
  86.  
  87. // Draw the line graph
  88. drawLineAndDots(c, index);
  89. }
  90.  
  91. /**
  92. * 画线
  93. * @param c
  94. * @param index
  95. */
  96. function drawLineAndDots(c, index){
  97. c.beginPath();
  98. c.strokeStyle = lineColour;
  99. c.moveTo(getXPixel(0), getYPixel(data[0].value));
  100. for(var i = 1; i < data.length; i ++) {
  101. // 使用直线
  102. //c.lineTo(getXPixel(i), getYPixel(data[i].value));
  103. //var cps = getControlPoints(getXPixel(i-1),getYPixel(data[i-1].value),getXPixel(i),getYPixel(data[i].value));
  104. //为了更美观一点 使用了弯曲的线
  105. c.bezierCurveTo(getXPixel(i-1)+9,getYPixel(data[i-1].value)+9,getXPixel(i)-9,getYPixel(data[i].value)-9,getXPixel(i), getYPixel(data[i].value))
  106.  
  107. /**
  108. // 线的阴影部分
  109. c.shadowBlur = lineShadowBlur;
  110. c.shadowOffsetX = lineShadowOffsetX;
  111. c.shadowOffsetY = lineShadowOffsetY;
  112. c.shadowColor = lineShadowColour;
  113. **/
  114.  
  115. }
  116.  
  117. c.stroke();
  118. c.shadowColor = "rgba( 0, 0, 0, 0 )";
  119. c.closePath();
  120. // Draw the dots
  121. c.fillStyle = dotsColour;
  122.  
  123. for(var i = 0; i < data.length; i ++) {
  124. // 有点中的节点
  125. if(i == index){
  126. c.beginPath();
  127. c.arc(getXPixel(i), getYPixel(data[i].value), 8, 0, Math.PI * 2, true);
  128. c.fill();
  129. c.textAlign = "center";
  130. c.font = chooseDotTextFont;
  131. c.fillText(data[i].X, xAxisLength + xPadding + 5 , 20 )
  132. c.fillText(data[i].value, xAxisLength + xPadding + 5 , 40 )
  133. }else{
  134. c.beginPath();
  135. c.arc(getXPixel(i), getYPixel(data[i].value), 4, 0, Math.PI * 2, true);
  136. c.fill();
  137. }
  138. divideXArray[i] = getXPixel(i) + dotsToDotsXLength/2;
  139. }
  140. }
  141.  
  142. function getMaxY() {
  143. var max = 0;
  144. for(var i = 0; i < data.length; i ++) {
  145. if(data[i].value > max) {
  146. max = data[i].value;
  147. }
  148. }
  149. max += 10 - max % 10;
  150. return max;
  151. }
  152.  
  153. /**
  154. * 计算x轴间距
  155. * @param val
  156. * @returns {number}
  157. */
  158. function getXPixel(val) {
  159. return (dotsToDotsXLength) * val + (xPadding * 1.5);
  160. }
  161.  
  162. /**
  163. * 计算y轴间距
  164. * @param val
  165. * @returns {number}
  166. */
  167. function getYPixel(val) {
  168. return lineChart.height - ((yAxisLength / getMaxYPoint(getMaxY())) * val) - yPadding;
  169. }
  170.  
  171. /**
  172. * 计算Y轴显示最大值
  173. * 输入1234 输出2000
  174. * @param maxY
  175. */
  176. function getMaxYPoint(maxY){
  177. var firstDigit = parseInt((maxY + '').substring(0,1)) + 1;
  178. var digitNum = parseInt((maxY+"").length);
  179. for(var i = 1; i<digitNum; i++){
  180. firstDigit = firstDigit *10
  181. }
  182. return firstDigit;
  183. }
  184.  
  185. /**
  186. * 计算Y轴坐标增加数量
  187. * @returns {number}
  188. */
  189. function getYSpace(){
  190. return getMaxYPoint(getMaxY())/5;
  191. }
  192.  
  193. /**
  194. * 格式化:三位数字加逗号
  195. * @param num
  196. * @returns {*}
  197. */
  198. function formatNum(num){
  199. if(!/^(\+|-)?\d+(\.\d+)?$/.test(num)){
  200. alert("wrong!");
  201. return num;
  202. }
  203. var re = new RegExp();
  204. re.compile("(\\d)(\\d{3})(,|\\.|$)");
  205. num += "";
  206. while(re.test(num)){
  207. num = num.replace(re, "$1,$2$3")
  208. }
  209. return num;
  210. }
  211.  
  212. //鼠标事件
  213. function handleDotsMousemoveEvent(mousemoveEvent){
  214. //取得鼠标位置
  215. var mouseX = mousemoveEvent.pageX - this.offsetLeft;
  216. var dot = 0;
  217. if(0 < mouseX && mouseX< xPadding){
  218. return;
  219. }
  220. if((xPadding + xAxisLength) < mouseX){
  221. return;
  222. }
  223. for(var i=0; i<divideXArray.length; i++){
  224.  
  225. if(mouseX < divideXArray[i]){
  226. dot = i;
  227. break;
  228. }
  229. }
  230. drawLineChart(dot);
  231. }
  232. }
效果:

 
 
 
 
 饼图:
里面有详细的解释。
注意以上网站上的源码无法直接使用所以 本人进行了部分的修改,以实现能够动态的处理后台传输的数据,并增加一个栏目,使功能完整。可以直接作为插件放入项目。
 

修改后的代码:(直接保存html文件即可)

  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <title>Pie Chart with HTML5 and jQuery - 1.0</title>
  5. <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
  6.  
  7. <style>
  8.  
  9. body {
  10. background: #fff;
  11. color: #333;
  12. font-family: "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
  13. font-size: 0.9em;
  14. padding: 40px;
  15. }
  16.  
  17. #container {
  18. width: 900px;
  19. margin: 0 auto;
  20. }
  21.  
  22. .chart, .chartData {
  23. border: 1px solid #333;
  24. background: #ebedf2 url("images/gradient.png") repeat-x 0 0;
  25. }
  26.  
  27. .chart {
  28. display: block;
  29. margin: 0 0 50px 0;
  30. float: left;
  31. cursor: pointer;
  32. }
  33.  
  34. .chartData {
  35. width: 200px;
  36. margin: 0 40px 0 0;
  37. float: right;
  38. border-collapse: collapse;
  39. box-shadow: 0 0 1em rgba(0, 0, 0, 0.5);
  40. -moz-box-shadow: 0 0 1em rgba(0, 0, 0, 0.5);
  41. -webkit-box-shadow: 0 0 1em rgba(0, 0, 0, 0.5);
  42. background-position: 0 -100px;
  43. }
  44.  
  45. .chartData th, .chartData td {
  46. padding: 0.5em;
  47. border: 1px dotted #666;
  48. text-align: left;
  49. }
  50.  
  51. .chartData th {
  52. border-bottom: 2px solid #333;
  53. text-transform: uppercase;
  54. }
  55.  
  56. .chartData td {
  57. cursor: pointer;
  58. }
  59.  
  60. .chartData td.highlight {
  61. background: #e8e8e8;
  62. }
  63.  
  64. .chartData tr:hover td {
  65. background: #f0f0f0;
  66. }
  67.  
  68. </style>
  69.  
  70. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  71. <!--[if IE]>
  72. <script src="http://explorercanvas.googlecode.com/svn/trunk/excanvas.js"></script>
  73. <![endif]-->
  74. </head>
  75. <body>
  76.  
  77. <div id="container">
  78.  
  79. <canvas id="chart" width="600" height="500" class="chart"></canvas>
  80.  
  81. <table id="chartData" class="chartData">
  82. <tr><th>Widget</th><th>Sales ($)</th><th>prcent (%)</th></tr>
  83. </table>
  84.  
  85. </div>
  86.  
  87. </body>
  88. </html>
  89. <script>
  90. var data=[{label:"SuperWidget",value:1862.12},{label:"MegaWidget1",value:1316.00},{label:"redasd",value:1300.00},{label:"hope",value:300.00},{label:"hack",value:300.00},{label:"MegaWidget",value:1316.00},{label:"redasd",value:1300.00},{label:"hope",value:300.00},{label:"hack",value:300.00}];
  91. // Run the code when the DOM is ready
  92. //$( pieChart );
  93. pieChart(data, 'chart', 'chartData');
  94.  
  95. function pieChart(data, chartElementId, chartTableElementId) {
  96.  
  97. // Config settings
  98. var chartSizePercent = 55; // The chart radius relative to the canvas width/height (in percent)
  99. var sliceBorderWidth = 1; // Width (in pixels) of the border around each slice
  100. var sliceBorderStyle = "#fff"; // Colour of the border around each slice
  101. var sliceGradientColour = "#ddd"; // Colour to use for one end of the chart gradient
  102. var maxPullOutDistance = 25; // How far, in pixels, to pull slices out when clicked
  103. var pullOutFrameStep = 4; // How many pixels to move a slice with each animation frame
  104. var pullOutFrameInterval = 40; // How long (in ms) between each animation frame
  105. var pullOutLabelPadding = 65; // Padding between pulled-out slice and its label
  106. var pullOutLabelFont = "bold 16px 'Trebuchet MS', Verdana, sans-serif"; // Pull-out slice label font
  107. var pullOutValueFont = "bold 12px 'Trebuchet MS', Verdana, sans-serif"; // Pull-out slice value font
  108. var pullOutValuePrefix = ""; // Pull-out slice value prefix
  109. var pullOutShadowColour = "rgba( 0, 0, 0, .5 )"; // Colour to use for the pull-out slice shadow
  110. var pullOutShadowOffsetX = 5; // X-offset (in pixels) of the pull-out slice shadow
  111. var pullOutShadowOffsetY = 5; // Y-offset (in pixels) of the pull-out slice shadow
  112. var pullOutShadowBlur = 5; // How much to blur the pull-out slice shadow
  113. var pullOutBorderWidth = 2; // Width (in pixels) of the pull-out slice border
  114. var pullOutBorderStyle = "#333"; // Colour of the pull-out slice border
  115. var chartStartAngle = -.5 * Math.PI; // Start the chart at 12 o'clock instead of 3 o'clock
  116.  
  117. // Declare some variables for the chart
  118. var canvas; // The canvas element in the page
  119. var currentPullOutSlice = -1; // The slice currently pulled out (-1 = no slice)
  120. var currentPullOutDistance = 0; // How many pixels the pulled-out slice is currently pulled out in the animation
  121. var animationId = 0; // Tracks the interval ID for the animation created by setInterval()
  122. var chartData = data; // Chart data (labels, values, and angles)
  123. var chartColours = []; // Chart colours (pulled from the HTML table)
  124. var totalValue = 0; // Total of all the values in the chart
  125. var canvasWidth; // Width of the canvas, in pixels
  126. var canvasHeight; // Height of the canvas, in pixels
  127. var centreX; // X-coordinate of centre of the canvas/chart
  128. var centreY; // Y-coordinate of centre of the canvas/chart
  129. var chartRadius; // Radius of the pie chart, in pixels
  130.  
  131. var chartElementId = chartElementId; // 圆饼元素id
  132. var chartTableElementId = chartTableElementId; // 数据表格元素id
  133.  
  134. // Set things up and draw the chart
  135. init();
  136.  
  137. /**
  138. * Set up the chart data and colours, as well as the chart and table click handlers,
  139. * and draw the initial pie chart
  140. */
  141.  
  142. function init() {
  143. var colors=['#FF4500','#0DA068','#194E9C','#ED9C13','#ED5713','#CD00CD','#7A378B','#B8860B','#8B2500','#9932CC','#5F91DC','#F88E5D','#0000FF','#B3EE3A','#7A378B','#FF1493','#F5DA81','#80FF00','#173B0B','#0B3B39','#0B0B3B','#A901DB','#6E6E6E','#5F04B4','#01DFD7','#A31A1A','#1A653C','#A49D0C','#790CA4','#CA80E8','#6E87D7','#D76ED2','#D7B86E','#49543B','#9EEBE8','#9ED9EB','#549B21']
  144. // Get the canvas element in the page
  145. canvas = document.getElementById(chartElementId);
  146.  
  147. // Exit if the browser isn't canvas-capable
  148. if ( typeof canvas.getContext === 'undefined' ) return;
  149.  
  150. // Initialise some properties of the canvas and chart
  151. canvasWidth = canvas.width;
  152. canvasHeight = canvas.height;
  153. centreX = canvasWidth / 2;
  154. centreY = canvasHeight / 2;
  155. chartRadius = Math.min( canvasWidth, canvasHeight ) / 2 * ( chartSizePercent / 100 );
  156.  
  157. // Grab the data from the table,
  158. // and assign click handlers to the table data cells
  159.  
  160. var currentRow = 0;
  161. var currentCell = 0;
  162. //$('#chartData').append('<tr><th>Widget</th><th>Sales ($)</th><th>prcent (%)</th></tr>')
  163. $.each(chartData, function(index,value){
  164. totalValue += value.value;
  165. });
  166. $.each(chartData, function(index,value){
  167. $('#'+chartTableElementId).append('<tr style="color: '+colors[index]+'"><td>'+value.label+'</td><td>'+value.value+'</td><td>'+ ( value.value / totalValue * 100 + .5 ).toFixed(2) + '%'+'</td></tr>')
  168.  
  169. });
  170.  
  171. $('#'+chartTableElementId+' td').each( function() {
  172. currentCell++;
  173. // Store the slice index in this cell, and attach a click handler to it
  174. $(this).data( 'slice', currentRow );
  175. $(this).click( handleTableClick );
  176. // Extract and store the cell colour
  177. if ( rgb = $(this).css('color').match( /rgb\((\d+), (\d+), (\d+)/) ) {
  178. chartColours[currentRow] = [ rgb[1], rgb[2], rgb[3] ];
  179. } else if ( hex = $(this).css('color').match(/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/) ) {
  180. chartColours[currentRow] = [ parseInt(hex[1],16) ,parseInt(hex[2],16), parseInt(hex[3], 16) ];
  181. } else {
  182. alert( "Error: Colour could not be determined! Please specify table colours using the format '#xxxxxx'" );
  183. return;
  184. }
  185. if(currentCell % 3 == 0){
  186. currentRow++;
  187. }
  188. } );
  189.  
  190. // Now compute and store the start and end angles of each slice in the chart data
  191.  
  192. var currentPos = 0; // The current position of the slice in the pie (from 0 to 1)
  193.  
  194. for ( var slice in chartData ) {
  195. chartData[slice]['startAngle'] = 2 * Math.PI * currentPos;
  196. chartData[slice]['endAngle'] = 2 * Math.PI * ( currentPos + ( chartData[slice]['value'] / totalValue ) );
  197. currentPos += chartData[slice]['value'] / totalValue;
  198. }
  199.  
  200. // All ready! Now draw the pie chart, and add the click handler to it
  201. drawChart();
  202. $('#'+chartElementId).click ( handleChartClick );
  203. }
  204.  
  205. /**
  206. * Process mouse clicks in the chart area.
  207. *
  208. * If a slice was clicked, toggle it in or out.
  209. * If the user clicked outside the pie, push any slices back in.
  210. *
  211. * @param Event The click event
  212. */
  213.  
  214. function handleChartClick ( clickEvent ) {
  215.  
  216. // Get the mouse cursor position at the time of the click, relative to the canvas
  217. var mouseX = clickEvent.pageX - this.offsetLeft;
  218. var mouseY = clickEvent.pageY - this.offsetTop;
  219.  
  220. // Was the click inside the pie chart?
  221. var xFromCentre = mouseX - centreX;
  222. var yFromCentre = mouseY - centreY;
  223. var distanceFromCentre = Math.sqrt( Math.pow( Math.abs( xFromCentre ), 2 ) + Math.pow( Math.abs( yFromCentre ), 2 ) );
  224.  
  225. if ( distanceFromCentre <= chartRadius ) {
  226.  
  227. // Yes, the click was inside the chart.
  228. // Find the slice that was clicked by comparing angles relative to the chart centre.
  229.  
  230. var clickAngle = Math.atan2( yFromCentre, xFromCentre ) - chartStartAngle;
  231. if ( clickAngle < 0 ) clickAngle = 2 * Math.PI + clickAngle;
  232.  
  233. for ( var slice in chartData ) {
  234. if ( clickAngle >= chartData[slice]['startAngle'] && clickAngle <= chartData[slice]['endAngle'] ) {
  235.  
  236. // Slice found. Pull it out or push it in, as required.
  237. toggleSlice ( slice );
  238. return;
  239. }
  240. }
  241. }
  242.  
  243. // User must have clicked outside the pie. Push any pulled-out slice back in.
  244. pushIn();
  245. }
  246.  
  247. /**
  248. * Process mouse clicks in the table area.
  249. *
  250. * Retrieve the slice number from the jQuery data stored in the
  251. * clicked table cell, then toggle the slice
  252. *
  253. * @param Event The click event
  254. */
  255.  
  256. function handleTableClick ( clickEvent ) {
  257. var slice = $(this).data('slice');
  258. toggleSlice ( slice );
  259. }
  260.  
  261. /**
  262. * Push a slice in or out.
  263. *
  264. * If it's already pulled out, push it in. Otherwise, pull it out.
  265. *
  266. * @param Number The slice index (between 0 and the number of slices - 1)
  267. */
  268.  
  269. function toggleSlice ( slice ) {
  270. if ( slice == currentPullOutSlice ) {
  271. pushIn();
  272. } else {
  273. startPullOut ( slice );
  274. }
  275. }
  276.  
  277. /**
  278. * Start pulling a slice out from the pie.
  279. *
  280. * @param Number The slice index (between 0 and the number of slices - 1)
  281. */
  282.  
  283. function startPullOut ( slice ) {
  284.  
  285. // Exit if we're already pulling out this slice
  286. if ( currentPullOutSlice == slice ) return;
  287.  
  288. // Record the slice that we're pulling out, clear any previous animation, then start the animation
  289. currentPullOutSlice = slice;
  290. currentPullOutDistance = 0;
  291. clearInterval( animationId );
  292. animationId = setInterval( function() { animatePullOut( slice ); }, pullOutFrameInterval );
  293.  
  294. // Highlight the corresponding row in the key table
  295. $('#'+chartTableElementId+' td').removeClass('highlight');
  296. var labelCell = $('#'+chartTableElementId+' td:eq(' + (slice*3) + ')');
  297. var valueCell = $('#'+chartTableElementId+' td:eq(' + (slice*3+1) + ')');
  298. var prcentCell = $('#'+chartTableElementId+' td:eq(' + (slice*3+2) + ')');
  299. labelCell.addClass('highlight');
  300. valueCell.addClass('highlight');
  301. prcentCell.addClass('highlight');
  302. }
  303.  
  304. /**
  305. * Draw a frame of the pull-out animation.
  306. *
  307. * @param Number The index of the slice being pulled out
  308. */
  309.  
  310. function animatePullOut ( slice ) {
  311.  
  312. // Pull the slice out some more
  313. currentPullOutDistance += pullOutFrameStep;
  314.  
  315. // If we've pulled it right out, stop animating
  316. if ( currentPullOutDistance >= maxPullOutDistance ) {
  317. clearInterval( animationId );
  318. return;
  319. }
  320.  
  321. // Draw the frame
  322. drawChart();
  323. }
  324.  
  325. /**
  326. * Push any pulled-out slice back in.
  327. *
  328. * Resets the animation variables and redraws the chart.
  329. * Also un-highlights all rows in the table.
  330. */
  331.  
  332. function pushIn() {
  333. currentPullOutSlice = -1;
  334. currentPullOutDistance = 0;
  335. clearInterval( animationId );
  336. drawChart();
  337. $('#'+chartTableElementId+' td').removeClass('highlight');
  338. }
  339.  
  340. /**
  341. * Draw the chart.
  342. *
  343. * Loop through each slice of the pie, and draw it.
  344. */
  345.  
  346. function drawChart() {
  347.  
  348. // Get a drawing context
  349. var context = canvas.getContext('2d');
  350.  
  351. // Clear the canvas, ready for the new frame
  352. context.clearRect ( 0, 0, canvasWidth, canvasHeight );
  353.  
  354. // Draw each slice of the chart, skipping the pull-out slice (if any)
  355. for ( var slice in chartData ) {
  356. if ( slice != currentPullOutSlice ) drawSlice( context, slice );
  357. }
  358.  
  359. // If there's a pull-out slice in effect, draw it.
  360. // (We draw the pull-out slice last so its drop shadow doesn't get painted over.)
  361. if ( currentPullOutSlice != -1 ) drawSlice( context, currentPullOutSlice );
  362. }
  363.  
  364. /**
  365. * Draw an individual slice in the chart.
  366. *
  367. * @param Context A canvas context to draw on
  368. * @param Number The index of the slice to draw
  369. */
  370.  
  371. function drawSlice ( context, slice ) {
  372.  
  373. // Compute the adjusted start and end angles for the slice
  374. var startAngle = chartData[slice]['startAngle'] + chartStartAngle;
  375. var endAngle = chartData[slice]['endAngle'] + chartStartAngle;
  376.  
  377. if ( slice == currentPullOutSlice ) {
  378.  
  379. // We're pulling (or have pulled) this slice out.
  380. // Offset it from the pie centre, draw the text label,
  381. // and add a drop shadow.
  382.  
  383. var midAngle = (startAngle + endAngle) / 2;
  384. var actualPullOutDistance = currentPullOutDistance * easeOut( currentPullOutDistance/maxPullOutDistance, .8 );
  385. startX = centreX + Math.cos(midAngle) * actualPullOutDistance;
  386. startY = centreY + Math.sin(midAngle) * actualPullOutDistance;
  387. context.fillStyle = 'rgb(' + chartColours[slice].join(',') + ')';
  388. context.textAlign = "center";
  389. context.font = pullOutLabelFont;
  390. context.fillText( chartData[slice]['label'], centreX + Math.cos(midAngle) * ( chartRadius + maxPullOutDistance + pullOutLabelPadding ), centreY + Math.sin(midAngle) * ( chartRadius + maxPullOutDistance + pullOutLabelPadding ) );
  391. context.font = pullOutValueFont;
  392. context.fillText( pullOutValuePrefix + chartData[slice]['value'] + " (" + ( chartData[slice]['value'] / totalValue * 100 + .5 ).toFixed(2) + "%)", centreX + Math.cos(midAngle) * ( chartRadius + maxPullOutDistance + pullOutLabelPadding ), centreY + Math.sin(midAngle) * ( chartRadius + maxPullOutDistance + pullOutLabelPadding ) + 20 );
  393. context.shadowOffsetX = pullOutShadowOffsetX;
  394. context.shadowOffsetY = pullOutShadowOffsetY;
  395. context.shadowBlur = pullOutShadowBlur;
  396.  
  397. } else {
  398.  
  399. // This slice isn't pulled out, so draw it from the pie centre
  400. startX = centreX;
  401. startY = centreY;
  402. }
  403.  
  404. // Set up the gradient fill for the slice
  405. var sliceGradient = context.createLinearGradient( 0, 0, canvasWidth*.75, canvasHeight*.75 );
  406. sliceGradient.addColorStop( 0, sliceGradientColour );
  407. sliceGradient.addColorStop( 1, 'rgb(' + chartColours[slice].join(',') + ')' );
  408.  
  409. // Draw the slice
  410. context.beginPath();
  411. context.moveTo( startX, startY );
  412. context.arc( startX, startY, chartRadius, startAngle, endAngle, false );
  413. context.lineTo( startX, startY );
  414. context.closePath();
  415. context.fillStyle = sliceGradient;
  416. context.shadowColor = ( slice == currentPullOutSlice ) ? pullOutShadowColour : "rgba( 0, 0, 0, 0 )";
  417. context.fill();
  418. context.shadowColor = "rgba( 0, 0, 0, 0 )";
  419.  
  420. // Style the slice border appropriately
  421. if ( slice == currentPullOutSlice ) {
  422. context.lineWidth = pullOutBorderWidth;
  423. context.strokeStyle = pullOutBorderStyle;
  424. } else {
  425. context.lineWidth = sliceBorderWidth;
  426. context.strokeStyle = sliceBorderStyle;
  427. }
  428.  
  429. // Draw the slice border
  430. context.stroke();
  431. }
  432.  
  433. /**
  434. * Easing function.
  435. *
  436. *
  437. * @param Number The ratio of the current distance travelled to the maximum distance
  438. * @param Number The power (higher numbers = more gradual easing)
  439. * @return Number The new ratio
  440. */
  441.  
  442. function easeOut( ratio, power ) {
  443. return ( Math.pow ( 1 - ratio, power ) + 1 );
  444. }
  445. };
  446.  
  447. </script>

总结:

 
1,我们完全可以只利用API画出自己想要的东西API
 
2,关于html5图表的插件有很多比如:国内的国外的
3,阅读网站:http://diveintohtml5.info/
 
4,不管html5以后发不发展,学点然后做个比较复杂的动画玩玩,也不错
 
 
 补充:
  鉴于项目压力,为了竟可能满足需求,可能最终我们不得不选择网上更加成熟的框架,但无论如何,本人还是希望能够完善出一个比较好的图表框架出来。
 
 
 

让我们继续前行

----------------------------------------------------------------------

努力不一定成功,但不努力肯定不会成功。
共勉。

html5实现饼图和线图-我们到底能走多远系列(34)的更多相关文章

  1. html5实现饼图和线图

    html5实现饼图和线图-我们到底能走多远系列(34) 我们到底能走多远系列(34) 扯淡: 送给各位一段话:     人生是一个不断做加法的过程     从赤条条无牵无挂的来     到学会荣辱羞耻 ...

  2. Spring mvc源码url路由-我们到底能走多远系列(38)

    我们到底能走多远系列38 扯淡: 马航的事,挺震惊的.还是多多珍惜身边的人吧. 主题: Spring mvc 作为表现层的框架,整个流程是比较好理解的,毕竟我们做web开发的,最早也经常接触的就是一个 ...

  3. node实现http上传文件进度条 -我们到底能走多远系列(37)

    我们到底能走多远系列(37) 扯淡: 又到了一年一度的跳槽季,相信你一定准备好了,每每跳槽,总有好多的路让你选,我们的未来也正是这一个个选择机会组合起来的结果,所以尽可能的找出自己想要的是什么再做决定 ...

  4. Sharded实现学习-我们到底能走多远系列(32)

    我们到底能走多远系列(32) 扯淡: 工作是容易的赚钱是困难的 恋爱是容易的成家是困难的 相爱是容易的相处是困难的 决定是容易的可是等待是困难的 主题: 1,Sharded的实现    Sharded ...

  5. 初始化IoC容器(Spring源码阅读)-我们到底能走多远系列(31)

    我们到底能走多远系列(31) 扯淡: 有个问题一直想问:各位你们的工资剩下来会怎么处理?已婚的,我知道工资永远都是不够的.未婚的你们,你们是怎么分配工资的? 毕竟,对自己的收入的分配差不多体现了自己的 ...

  6. JMS生产者+单线程发送-我们到底能走多远系列(29)

    我们到底能走多远系列(29) 扯淡: “然后我俩各自一端/望着大河弯弯/终于敢放胆/嘻皮笑脸/面对/人生的难”      --- <山丘> “迎着风/迎向远方的天空/路上也有艰难/也有那解 ...

  7. ArrayBlockingQueue-我们到底能走多远系列(42)

    我们到底能走多远系列(42) 扯淡: 乘着有空,读些juc的源码学习下.后续把juc大致走一边,反正以后肯定要再来. 主题: BlockingQueue 是什么 A java.util.Queue t ...

  8. ThreadPoolExecutor机制探索-我们到底能走多远系列(41)

    我们到底能走多远系列(41) 扯淡: 这一年过的不匆忙,也颇多感受,成长的路上难免弯路,这个世界上没人关心你有没有变强,只有自己时刻提醒自己,不要忘记最初出发的原因. 其实这个世界上比我们聪明的人无数 ...

  9. 服务调用方案(Spring Http Invoker) - 我们到底能走多远系列(40)

    我们到底能走多远系列(40) 扯淡:  判断是否加可以效力于这家公司,一个很好的判断是,接触下这公司工作几年的员工,了解下生活工作状态,这就是你几年后的状态,如果满意就可以考虑加入了. 主题: 场景: ...

随机推荐

  1. hibernate generator class=xxx id详解

    <id>元素中的<generator>用来为该持久化类的实例生成唯一的标识,hibernate提供了很多内置的实现.Increment:由hibernate自动递增生成标识符, ...

  2. ext DateTime.js在ie下显示不全

    问题: ext在使用DateTime.js的时候会出现在日期控件在ie下显示不完成.如图  少了底部的“今天按钮”. 解决方法: 在ext/ux/form/DateTime.js (我的是这个路径,根 ...

  3. Drag+Drop和MouseClick

    项目中的一个树形结节,既要响应拖拽事件.又要响应点击事件.实现的时候没多想,依次实现了tree_MouseClick.tree_MouseDown.tree_MouseMove事件.出现的Bug是,偶 ...

  4. java枚举类

    enum关键字用于定义枚举类,若枚举只有一个成员, 则可以作为一种单例模式的实现方式.   枚举类对象的属性不应允许被改动, 所以应该使用 private final 修饰. 枚举类的使用 priva ...

  5. Codeforces Round #326 (Div. 2)-Duff in Love

    题意: 一个数x被定义为lovely number需要满足这样的条件:不存在一个数a(a>1),使得a的完全平方是x的因子(即x % a2  != 0). 给你一个数n,求出n的因子中为love ...

  6. C++指针详解(二)

    指针是C/C++编程中的重要概念之一,也是最容易产生困惑并导致程序出错的问题之一.利用指针编程可以表示各种数据结构,通过指针可使用主调函数和被调函数之间共享变量或数据结构,便于实现双向数据通讯:指针能 ...

  7. dialog参数、方法以及事件

    参数(options) DOM方式初始化dialog的,推荐使用集合属性data-options定义参数,如果使用data属性定义参数,注意转换成对应的名称. 名称 类型 默认值 描述 id stri ...

  8. ios 检测应用程序升级问题

    app 上其实已经有自动检测我们版本的功能.  其实我也觉得对于一个程序员来说检测功能让,系统来维护更合适和合理.开发者只要告诉苹果即可. 然而今天老大非要实现自己版本更新的问题,因此也查找了相关的资 ...

  9. 2013年8月份第3周51Aspx源码发布详情

    BaiduMusic Cache源码  2013-8-23 [VS2012]功能介绍:可以读取并保存百度音乐(Win8应用程序商店版本)的缓存.可以检测电脑是否安装了百度音乐,支持缓存音乐的导出功能. ...

  10. keil(持续更新)

    1函数格式提示 2  cording时有警告和错误提示 3 类的成员 提示