使用 HTML5 和 jQuery 绘制 ASP.NET 图表






4.73/5 (25投票s)
如何使用 ASP.NET、HTML5 和 jQuery 绘制我们的图表
引言
在我之前的文章 使用 HTML5 Canvas 在 ASP.NET 中创建 Web 绘画工具 中,我解释了如何使用 HTML5 和jQuery创建一个简单的 Web 绘画工具。我参考了 几个参考网站,使用 HTML5 和jQuery绘制了一个简单的图表。
可能会有人问,既然市面上有很多免费和第三方图表可用,为什么我们还需要自己绘制图表?
这个问题的答案是,即使有很多免费的图表控件可用,但有时并非所有图表控件都能满足我们的需求。
例如,如果我们想在图表中添加自己的水印,如果我们想显示自己的警报状态图像,或者如果我们想在图表中添加公司徽标等。
很难找到满足所有这些额外需求的图表控件。使用其他图表控件无法进行自定义。设想一下,如果我们自己绘制和设计图表控件并在我们的项目中加以使用。我们可以添加所有功能的限制将在于我们的想象力。
因此,我考虑使用 ASP.NET、HTML5 和jQuery来绘制具有以下功能的图表。
在源文件 zip 压缩包中,您会找到 Visual Studio 2010 和 Visual Studio 2013 的解决方案。您可以根据您的 Visual Studio 版本使用任何一个解决方案。
在本文中,我们将看到如何使用 HTML5 和jQuery绘制以下图表:
- 折线图
- 条形图
- 折线图 & 柱状图
- 饼图
- 甜甜圈图
- 气泡图
我的柱状图功能
以下所有功能将用于所有图表类型。我们将在代码部分逐一查看。
图表源数据
绘图数据可以来自数据库/数据表/列表/XML 文件或任何其他取决于您需求的数据源。您只需要做的是从您的源获取数据,并将结果绑定到下拉列表(包含值和文本。此处,值将是用于绘图的整数,文本将显示在标签上)。
图表类别数量
这里,我将图表类别显示限制在最少 1 个到最多 12 个。这意味着我们可以根据数据源动态加载绘图类别。但有所限制,因为显示绘图值最多为 12 个绘图。(但用户可以根据需求轻松重新设计代码。)
图表标题文本
用户可以添加自己的图表标题,并在需要时动态更改标题。在我的示例中,我将在柱状图的底部绘制“标题文本框”的文本。(用户可以根据需求重新设计和自定义此功能。)
图表水印文本
在某些情况下,我们需要将公司名称作为水印添加到我们的柱状图中。在我的示例中,我将在柱状图的中心绘制水印文本框的文本。(用户可以根据需求重新设计和自定义此功能。)
图表公司 LOGO
用户可以添加自己的公司徽标到图表中。(这里我添加了我自己的图片作为顶部右角的徽标。(用户可以根据需要重新设计和自定义此功能)。
图表警报图像
图表警报图像显示:您从文章的第一张图像中可以看到带有标签。我显示了柱状图的标签文本和警报图像。如果选中“警报开启”单选按钮,我将显示警报图像。如果点击“警报关闭”单选按钮,则警报图像将不会显示。
警报图像有什么用?
让我们考虑一个实际项目。例如,我们需要为一家制造工厂显示一个包含生产结果(良好和不良)的饼图。例如,如果每个质量值的生产结果高于 300,那么我们需要显示警报绿色图像,如果质量值低于 300,那么我们需要显示带有标签条的红色图像。
这个警报图像可以轻松识别每个质量结果是好还是坏。(在这里,我使用了两个质量检查并使用绿色和红色图像进行显示,但用户可以根据需求进行自定义并添加自己的图像和逻辑。)
图表颜色主题
用户可以选择一种颜色主题,如绿色主题或蓝色主题。
图例显示
用户可以使用复选框启用或禁用图表的图例显示。如果选中“显示图例”复选框,则图表将显示标签和警报图像。如果未选中,则图表中将不显示图例。
将图表保存为图像
用户可以将图表保存为图像。
Using the Code
步骤 1:创建新的 ASP.NET Web 项目
点击开始程序,然后打开Visual Studio 2013或Visual Studio 2010(取决于您安装的版本),选择其中一个。点击“文件” -> “新建” -> “项目…”,然后选择ASP.NET WEB 项目,然后点击创建。
步骤 2:将 Canvas 标签添加到您的 Webform
添加一个新的 Webform,并在Section
标签内添加一个Canvas 元素
。
<SECTION style="border-style: solid; border-width: 2px; width: 800px;">
<CANVAS HEIGHT="600px" WIDTH="800px" ID="canvas">
Your browser is not supporting HTML5 Canvas .Upgrade Browser to
view this program or check with Chrome or in Firefox.
</CANVAS>
</SECTION>
步骤 3:逐步编写脚本绘制图表
- 脚本全局变量:首先,在脚本标签内添加绘制图表所需的全局变量。
我已为每个变量在其前面注释了其用途。这里,
ChartWidth
和chartHeight
变量将用于存储和绘制图表的宽度和高度,具体取决于Canvas
的大小。//public Canvas object to use in all the functions. //this variable will be used to check for the result of Alert Image display var alertCheckValue = 300; //Adding the Pic Chart Colors to array .Here i have fixed to 12 colors //and 12 datas to add as Pic Chart.if you want you can add more from here. var pirChartColor = ["#6CBB3C", "#F87217", "#EAC117", "#EDDA74", "#CD7F32", "#CCFB5D", "#FDD017", "#9DC209", "#E67451", "#728C00", "#617C58", "#64E986"]; // green Color Combinations // var pirChartColor = ["#3090C7", "#BDEDFF", "#78C7C7", // "#736AFF", "#7FFFD4", "#3EA99F", "#EBF4FA", // "#F9B7FF", "#8BB381", "#BDEDFF", "#B048B5", // "#4E387E"]; // Blue Color Combinations var lineColor = "#3090C7"; var lineOuterCircleColor = "#6CBB3C"; var lineInnerCircleColor = "#FFFFFF"; // declare the Canvas object var canvas; var chartCTX; // declare the Border Space,Chart Start X and Y Position; var xSpace = 80; var ySpace = 80; // declare the Chart DrawWidth and Height var chartWidth, chartHeight; // declare the Chart Legend Width and Height var legendWidth, legendHeight; //declare the Chart data Minimum Value, //maximum Value and Noofplots(Bars/Arc and Line points) var minDataVal, maxDataVal, noOfPlots; // here, we declare the Image for the Chart legend alert status display. var greenImage = new Image(); var redImage = new Image(); // Alert Image Size width and height var imagesize = 20; var maxValdivValue; // Here, we declare the X,YAxis Font size and Color var fotnColor = "#000000"; var axisfontSize = 10; var LogoImage = new Image(); var LogoImgWidth = 120; var LogoImgHeight = 70; // This array will be used to draw the Legends rect = {}; rectInner = {};
“注意:我使用了母版页,所以脚本中每个控件的前面,我都会使用
ContentPlaceHolderID
。例如,我的绿色主题单选按钮 ID 是
rdoColorGreen
。但对于 jQuery,它将这样使用cphBody_rdoColorGreen
。例如,如果我们使用母版页,那么我们在脚本中像这样添加
ContentPlaceHolderID
。if ($('#cphBody_rdoColorGreen:checked').val() == "rdoColorGreen") { }
如果我们没有使用母版页,并且我们在 Webform 中绘制图表而不包含母版页,那么我们需要像这样删除
contentplaceholder
ID。if ($('# rdoColorGreen:checked').val() == "rdoColorGreen") { }
- 图表颜色主题:在此方法中,根据用户从单选按钮中选择的颜色,我将选择颜色数组来填充每个绘图的颜色。这是一个通用函数,可用于绘制任何图表,如折线图、柱状图、饼图、甜甜圈图等。
function ChangeChartColor() { if ($('#cphBody_rdoColorGreen:checked').val() == "rdoColorGreen") { pirChartColor = ["#6CBB3C", "#F87217", "#EAC117", "#EDDA74", "#CD7F32", "#CCFB5D", "#FDD017", "#9DC209", "#E67451", "#728C00", "#617C58", "#64E986"]; // green Color Combinations lineColor = "#3090C7"; // Blue Color for Line lineOuterCircleColor = "#6CBB3C"; // Green Color for Outer Circle } else { pirChartColor = ["#3090C7", "#BDEDFF", "#78C7C7", "#736AFF", "#7FFFD4", "#3EA99F", "#EBF4FA", "#F9B7FF", "#8BB381", "#BDEDFF", "#B048B5", "#4E387E"]; // Blue Color Combinations lineColor = "#F87217"; // Orange Color for the Line lineOuterCircleColor = "#F70D1A "; // Red Color for the outer circle } }
- 图表颜色主题:此方法将用于获取绘制图表的
X
和Y
点。这是一个通用函数,可用于绘制任何图表,如折线图、柱状图、饼图、甜甜圈图等。function getXPlotvalue(val) { return (Math.round((chartWidth - xSpace) / noOfPlots)) * val + (xSpace * 1.5)-24; } // Return the y pixel for a graph point function getYPlotVale(val) { return chartHeight - (((chartHeight - xSpace) / maxDataVal) * val); }
- 绘制图例:此方法将用于绘制图表的图例。在此方法中,我将绘制带有颜色的标签,并在标签内添加标签文本和警报图像。这是一个通用函数,可用于绘制任何图表,如折线图、柱状图、饼图、甜甜圈图等。(在折线图中,我不使用此图例,因为折线图不需要显示标签。)
// This function is used to draw the Legend function drawLengends() { ctx.fillStyle = "#7F462C"; ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h); //Drawing Inner White color Rectangle with in above brown rectangle //to plot all the Labels with color,Text and Value. ctx.fillStyle = "#FFFFFF"; rectInner.startX = rect.startX + 1; rectInner.startY = rect.startY + 1; rectInner.w = rect.w - 2; rectInner.h = rect.h - 2; ctx.fillRect(rectInner.startX, rectInner.startY, rectInner.w, rectInner.h); labelBarX = rectInner.startX + 4; labelBarY = rectInner.startY + 4; labelBarWidth = rectInner.w - 10; labelBarHeight = (rectInner.h / noOfPlots) - 5; colorval = 0; // here to draw all the rectangle for Labels with Image display $('#cphBody_DropDownList1 option').each(function () { ctx.fillStyle = pirChartColor[colorval]; ctx.fillRect(labelBarX, labelBarY, labelBarWidth, labelBarHeight); // Here we check for the rdoAlert Status is On - If the Alert is on, // then we display the Alert Image as per the Alert check value. if ($('#cphBody_rdoAlaramOn:checked').val() == "rdoAlaramOn") { // Here we can see for ever chart value we check with the condition. // We have initially declare the alertCheckValue as 300. // so if the Chart Plot value is Greater than or // equal to the check value // then we display the Green Image else we display the Red Image. // user can change this to your requirement if needed. // This is optional function for the Pie Chart. if (parseInt($(this).val()) >= alertCheckValue) { ctx.drawImage(greenImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize); } else { ctx.drawImage(redImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize); } } //Draw the Pie Chart Label text and Value ctx.fillStyle = "#000000"; ctx.font = '10pt Calibri'; ctx.fillText($(this).text(), labelBarX + imagesize + 2, labelBarY + (labelBarHeight / 2)); // To Increment and draw the next bar ,label Text and Alert Image. labelBarY = labelBarY + labelBarHeight + 4; // labelTextYXVal = labelBarY + labelBarHeight - 4; colorval = colorval + 1; }); }
- 绘制图表:这是主方法。在按钮“绘制图表图像”点击时,我将首先调用此方法,在该方法中,我将根据需要调用其他方法。
在此方法中,我在每个代码前都进行了注释说明。该方法包含五个主要代码部分,我们可以看到这里。在注释中,我分步解释了每个部分。
- 首先,我们计算并存储所有必要的变量,如项最大值、项总数、图表宽度、图表高度、图例宽度、图例高度等。
- 绘制图例。
- 将图表标题和徽标添加到图表中。
- 绘制带绘图文本的 X 轴线。
- 绘制带 Y 轴绘图值的 Y 轴线。
- 绘制柱状图方法(接下来,我们调用需要绘制为我们图表的方法。对于每种图表,我都创建了一个单独的方法。例如,要绘制柱状图,我将调用“
drawBarChart()
”方法;要绘制折线图,我将调用“drawLineChart()
”方法,等等。 - 绘制图表的水印文本。
// This is the main function to draw the Charts function drawChart() { ChangeChartColor(); // assign the images path for both Alert images greenImage.src = '../images/Green.png'; redImage.src = '../images/Red.png'; LogoImage.src = '../images/shanu.jpg'; // Get the minimum and maximum value.here i have used the hidden field // from code behind which will stored the Maximum and // Minimum value of the Drop down list box. minDataVal = $('#cphBody_hidListMin').val(); maxDataVal = $('#cphBody_hidListMax').val(); // Total no of plots we are going to draw. noOfPlots = $("#cphBody_DropDownList1 option").length; maxValdivValue = Math.round((maxDataVal / noOfPlots)); //storing the Canvas Context to local variable ctx. //This variable will be used to draw the Pie Chart canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); //globalAlpha - > is used to display the 100% opacity of chart. //Because at the bottom of the code, //I have used the opacity to 0.1 to display the water mark text //with fade effect. ctx.globalAlpha = 1; ctx.fillStyle = "#000000"; ctx.strokeStyle = '#000000'; //Every time we clear the canvas and draw the chart ctx.clearRect(0, 0, canvas.width, canvas.height); //If need to draw with out legend for the Line Chart chartWidth = canvas.width - xSpace; chartHeight = canvas.height - ySpace; // step 1) Draw legend $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ // ######################## if ($('#cphBody_chkLegend:checked').val() == "on") { chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2)); chartHeight = canvas.height - ySpace - 10; legendWidth = canvas.width - ((canvas.width / 3) - xSpace); legendHeight = ySpace; rect.startX = legendWidth; rect.startY = legendHeight; rect.w = canvas.width / 3 - xSpace - 10; rect.h = canvas.height - ySpace - 10; //In this method, I will draw the legend with the Alert Image. drawLengends(); } // end step 1) $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ var chartMidPosition = chartWidth / 2 - 60; //// //If need to draw with legend //// chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2)); //// chartHeight = canvas.height - ySpace - 10; // Step 2 ) +++++++++++++ To Add Chart Title and Company Logo //To Add Logo to Chart var logoXVal = canvas.width - LogoImgWidth - 10; var logolYVal = 0; //here we draw the Logo for the chart and I have used the alpha //to fade and display the Logo. ctx.globalAlpha = 0.6; ctx.drawImage(LogoImage, logoXVal, logolYVal, LogoImgWidth, LogoImgHeight); ctx.globalAlpha = 1; ctx.font = '22pt Calibri'; ctx.fillStyle = "#15317E"; ctx.fillText($('#cphBody_txtTitle').val(), chartMidPosition, chartHeight + 60); ctx.fillStyle = "#000000"; ctx.font = '10pt Calibri'; // end step 2) +++++++++++ End of Title and Company Logo Add // Step 3 ) +++++++++++++ toDraw the X-Axis and Y-Axis // >>>>>>>>> Draw Y-Axis and X-Axis Line(Horizontal Line) // Draw the axes ctx.beginPath(); ctx.moveTo(xSpace, ySpace); // first Draw Y Axis ctx.lineTo(xSpace, chartHeight); // Next draw the X-Axis ctx.lineTo(chartWidth, chartHeight); ctx.stroke(); // >>>>>>>>>>>>> End of X-Axis Line Draw //end step 3) +++++++++++++++++++++++ // Step 4) <<<<<<<<<<<<<<<<<<<<<<< // To Draw X - Axis Plot Values <<<<<<<<<<<<< }}}}}} // Draw the X value texts // --->>>>>>>>>>>> // for the Bar Chart i have draw the X-Axis plot in drawBarChart // <<<<<<<<<<<<<<<<<<<<<<< End of X Axis Draw // end Step 4) <<<<<<<<<<<<<<<<<<<<<<< // Step 5){{{{{{{{{{{{ // {{{{{{{{{{{{{To Draw the Y Axis Plot Values}}}}}}}}}}}}}} var vAxisPoints = 0; var max = maxDataVal; max += 10 - max % 10; for (var i = 0; i <= maxDataVal; i += maxValdivValue) { ctx.fillStyle = fotnColor; ctx.font = axisfontSize + 'pt Calibri'; ctx.fillText(i, xSpace - 40, getYPlotVale(i)); //Here we draw the Y-Axis point line ctx.beginPath(); ctx.moveTo(xSpace, getYPlotVale(i)); ctx.lineTo(xSpace - 10, getYPlotVale(i)); ctx.stroke(); vAxisPoints = vAxisPoints + maxValdivValue; } //{{{{{{{{{{{{{{ End of Y- Axis Plot Values //end Step 5) {{{{{{{{{{{{{{{{{{ //Step 5) ********************************************************* //Function to Draw our Chart here we can //Call/Bar Chart/Line Chart or Pie Chart // to Draw Bar Chart drawBarChart(); // to Draw line Chart drawLineChart(); // end step 6) ************** //Step 7) :::::::::::::::::::: to add the Water mark Text // Here add the Water mark text at center of the chart ctx.globalAlpha = 0.1; ctx.font = '86pt Calibri'; ctx.fillStyle = "#000000"; ctx.fillText($('#cphBody_txtWatermark').val(), chartMidPosition - 40, chartHeight / 2); ctx.font = '10pt Calibri'; ctx.globalAlpha = 1; /// end step 7) :::::::::::::::::::::::::::::::::::::: }
在这里,我们将逐一查看用于绘制图表的整个方法。
绘制柱状图:在此方法中,我将计算所有数据以及绘图的 x 和 y 点,并逐个绘制矩形以绘制柱状图。
function drawBarChart() { var XvalPosition = xSpace; widthcalculation = parseInt(((parseInt(chartWidth) - 100) / noOfPlots)); colorval = 0; $('#cphBody_DropDownList1 option').each(function () { // Draw Xaxis Plots Line and Text *********** XvalPosition = XvalPosition + widthcalculation; ctx.moveTo(XvalPosition, chartHeight); ctx.lineTo(XvalPosition, chartHeight + 15); ctx.stroke(); ctx.fillStyle = "#000000"; ctx.font = '10pt Calibri'; ctx.fillText('Bar' + parseInt(colorval + 1), XvalPosition - 28, chartHeight + 24); // End Xval Plotting ************ //Draw Bar Graph **************==================******************** var barRatio = parseInt($(this).val()) / maxDataVal; var barfillHeight = parseInt(barRatio * (parseInt(chartHeight - xSpace))); ctx.fillRect(XvalPosition - widthcalculation - 1, chartHeight - 1, widthcalculation + 2, -barfillHeight); ctx.fillStyle = pirChartColor[colorval]; // e.DrawRectangle(B1pen, XvalPosition_Start, // Ystartval, XvalPosition_new, YEndval); ctx.fillRect(XvalPosition - widthcalculation, chartHeight, widthcalculation, -barfillHeight); //ctx.fillRect(XvalPosition - widthcalculation, //yLineHeight, widthcalculation, yLineHeight- parseInt($(this).val())); // ***** ////// ctx.fillStyle = "#000000"; ////// ctx.font = '10pt Calibri'; ////// ctx.fillText($(this).val(), ////// XvalPosition - widthcalculation + 4, ////// chartHeight - barfillHeight - 8); ctx.fillStyle = pirChartColor[colorval]; //END Draw Bar Graph **************==================******************** colorval = colorval + 1; }); }
绘制折线图:在此方法中,我将计算所有数据以及绘图的 x 和 y 点,并为每条折线绘制带有点和项文本的折线。
function drawLineChart() { // For Drawing Line ctx.lineWidth = 3; var value = $('select#cphBody_DropDownList1 option:selected').val(); ctx.beginPath(); // *************** To Draw the Line and Plot Value in Line ctx.fillStyle = "#FFFFFF"; ctx.strokeStyle = '#FFFFFF'; ctx.moveTo(getXPlotvalue(0), getYPlotVale(value)); ctx.fillStyle = "#000000"; ctx.font = '12pt Calibri'; ctx.fillText(value, getXPlotvalue(0), getYPlotVale(value) - 12); var ival = 0; $('#cphBody_DropDownList1 option').each(function () { if (ival > 0) { ctx.lineTo(getXPlotvalue(ival), getYPlotVale($(this).val())); ctx.stroke(); ctx.fillStyle = "#000000"; ctx.font = '12pt Calibri'; ctx.fillText($(this).val(), getXPlotvalue(ival), getYPlotVale($(this).val()) - 16); } ival = ival + 1; ctx.fillStyle = lineColor; ctx.strokeStyle = lineColor; }); // *************** To Draw the Line Dot Circle //For Outer Blue Dot ival = 0; $('#cphBody_DropDownList1 option').each(function () { ctx.fillStyle = lineOuterCircleColor; ctx.strokeStyle = lineOuterCircleColor; ctx.beginPath(); ctx.arc(getXPlotvalue(ival), getYPlotVale($(this).val()), 7, 0, Math.PI * 2, true); ctx.fill(); ctx.fillStyle = lineInnerCircleColor; ctx.strokeStyle = lineInnerCircleColor; ctx.beginPath(); ctx.arc(getXPlotvalue(ival), getYPlotVale($(this).val()), 4, 0, Math.PI * 2, true); ctx.fill(); ival = ival + 1; }); ctx.lineWidth = 1; }
绘制饼图:与柱状图类似,在这里我将计算所有点,并使用“
arc
”方法绘制饼图。function drawPieChart() { var lastend = 0; var XvalPosition = xSpace; chartWidth = (canvas.width / 2) - xSpace; chartHeight = (canvas.height / 2) - (xSpace / 2); widthcalculation = parseInt(((parseInt(chartWidth) - 100) / noOfPlots)); //Draw Xaxis Line //-- draw bar X-Axis and Y-Axis Line var XLineStartPosition = xSpace; var yLineStartPosition = xSpace; var yLineHeight = chartHeight; var xLineWidth = chartWidth; colorval = 0; var chartTotalResult = getChartTotal(); $('#cphBody_DropDownList1 option').each(function () { ctx.fillStyle = pirChartColor[colorval]; ctx.beginPath(); ctx.moveTo(chartWidth, chartHeight); //Here we draw the each Pic Chart arc with values and size. ctx.arc(chartWidth, chartHeight + 6, chartHeight, lastend, lastend + (Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult)), false); ctx.lineTo(chartWidth, chartHeight); ctx.fill(); lastend += Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult); //END Draw Bar Graph **************==================******************** colorval = colorval + 1; }); }
绘制甜甜圈图:与饼图类似。在这里,我将计算所有点,并使用“
arc
”方法绘制饼图。要绘制甜甜圈形状,我们使用“donutoutcircle
”和“donutInnsercircle
”值。在这里,我将检查图表宽度和高度。我将绘制甜甜圈图的大小。function drawDonutChart() { var lastend = 0; var XvalPosition = xSpace; chartWidth = (canvas.width / 2) - xSpace; chartHeight = (canvas.height / 2) - (xSpace / 2); widthcalculation = parseInt(((parseInt(chartWidth) - 100) / noOfPlots)); var donutOutercircle = chartHeight / 2; var donutinnersircle = (chartWidth / 2) + xSpace; colorval = 0; var chartTotalResult = getChartTotal(); var legend1 = 0; $('#cphBody_DropDownList1 option').each(function () { ctx.fillStyle = pirChartColor[colorval]; legend1 += (Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult)); //---- ctx.beginPath(); ctx.moveTo(chartWidth, chartWidth); ctx.arc(chartWidth, chartWidth, donutOutercircle, lastend, legend1, false); // Outer: CCW ctx.arc(chartWidth, chartWidth, donutinnersircle, legend1, lastend, true); // Inner: CW //------ ctx.fill(); lastend += Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult); //END Draw Bar Graph **************==================******************** colorval = colorval + 1; }); }
绘制气泡图:与折线图类似,我们绘制气泡图,但这里使用“
arc
”方法绘制每个项的圆。// to Draw Bubble Chart function drawBubbleChart() { // *************** To Draw the Line Dot Circle ctx.globalAlpha = 0.8; //For Outer Blue Dot var bubbleSize = 40; ival = 0; $('#cphBody_DropDownList1 option').each(function () { ctx.fillStyle = pirChartColor[ival]; ctx.strokeStyle = pirChartColor[ival]; ctx.beginPath(); ctx.arc(getXPlotvalue(ival) + 14, getYPlotVale($(this).val()), bubbleSize, bubbleSize, Math.PI * 2, true); ctx.fill(); ival = ival + 1; }); ctx.lineWidth = 1; }
- 保存图表:在
Save
方法中,我首先检查浏览器版本。如果浏览器不是 IE(即 Chrome 或 Firefox),那么使用“canvas.toDataURL
”方法保存图像。因为此方法在 Internet Explorer 中不起作用,所以对于“Internet Explorer”,然后使用 Ajaxpost
方法保存图像。function ShanuSaveImage() { var m = confirm("Are you sure to Save "); if (m) { if (navigator.appName == 'Microsoft Internet Explorer') { var image_NEW = document.getElementById ("canvas").toDataURL("image/png"); image_NEW = image_NEW.replace('data:image/png;base64,', ''); $.ajax({ type: 'POST', contentType: 'application/json; charset=utf-8', url: '/shanuHTML5PIEChart.aspx/SaveImage', data: '{ "imageData" : "' + image_NEW + '" }', async: false, success: function (msg) { alert(msg.d); }, error: function () { alert("Pie Chart Not Saved"); } }); } else { // save image without file type var canvas = document.getElementById("canvas"); document.location.href = canvas.toDataURL("image/png").replace ("image/png", "image/octet-stream"); var ImageSave = document.createElement('a'); ImageSave.download = "shanuPIEImage.png"; ImageSave.href = canvas.toDataURL("image/png").replace ("image/png", "image/octet-stream"); ImageSave.click(); alert("Image Saved"); } } }
- 从 DataTable 绑定下拉列表数据:在页面加载和按钮点击时,我将调用“
BindDropDownList()
”方法来填充DataTable
中的 PIE 图表值,并将最终结果绑定到下拉列表。这里,我使用
DataTable
来填充数据并将其绑定到下拉列表,作为一个简单的示例。您可以编写自己的代码将结果绑定到下拉列表。您甚至可以根据需要将源从下拉列表更改为任何控件。
JavaScript 将获取此下拉列表项,并使用这些值动态创建饼图。
protected void Page_Load(object sender, EventArgs e) { BindDropDownList(); } protected void Button1_Click(object sender, EventArgs e) { BindDropDownList(); } private void BindDropDownList() { DataTable dt = new DataTable(); dt.Clear(); dt.Rows.Clear(); dt.Columns.Add("Names"); dt.Columns.Add("Frequency"); dt.Columns["Frequency"].DataType = Type.GetType("System.Int32"); Random random = new Random(); for (int i = 1; i <=Convert.ToInt32(txtChartCount.Text.Trim()); i++) { DataRow row = dt.NewRow(); Int32 value = random.Next(100, 600); row["Names"] = "Bar-" + i.ToString() + " - (" + value+") "; row["Frequency"] = value; dt.Rows.Add(row); } DropDownList1.DataSource = dt; DropDownList1.DataTextField = "Names"; DropDownList1.DataValueField = "Frequency"; DropDownList1.DataBind(); }
测试过的浏览器
- Chrome
- Firefox
- IE10
输出
折线图
气泡图
甜甜圈图
关注点
我们可以使用相同的逻辑来创建 Winform 版本图表控件。例如,您可以查看我为 Windows 窗体版本创建的 Pareto 图表控件。
使用 HTML5 真的很有趣。我希望您喜欢阅读我的文章。如果有人能从我的文章中受益,我将感到非常高兴。
历史
- 2015 年 4 月 2 日:初始版本