Chart.js uses

Download chart.js and put it directly on your web page:

https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js

First of all, you need to have a label in the page, canvas, this is the canvas, you can treat it as a picture, for example, insert it somewhere in HTML like this:

<canvas id="season"></canvas>

Get data from MySql database and use chart.js to draw column chart.

File structure:


1. The index.php file.Get data from database. First connect to the database exercisedata, then query the student's name userName and the student's score from the users table of the database, and give the alias label and value to the userName and score to conform to the data format required when drawing graphs in chart.js. After executing the sql statement, return the result in json format. code show as below:

<span style="font-size:18px;"> <?php
//database configuration
$dbconf= array(  
        'host'=>'127.0.0.1',  
        'user'=>'root',  
        'password'=>'123456',//Because of the test, I will not set a password. In actual development, a new user must be created and a password set  
        'dbName'=>'exercisedata',  
        'charSet'=>'utf8',  
        'port'=>'3306' );
function openDb($dbConf){      $conn=mysqli_connect($dbConf['host'],$dbConf['user'],$dbConf['password'],$dbConf['dbName'],$dbConf['port']) or die('打开失败');  
    //Of course, if you do not fill in the database above, you can also select the database through mysqli_select($conn, $dbConf['dbName'])  
    mysqli_set_charset($conn,$dbConf['charSet']);//Set encoding  
    return $conn;  
}
$conn=openDb($dbconf);  
//2query method executes adding, checking, deleting, and modifying  
$sql='SELECT userName as `label`, score as `value` FROM exercisedata.users';  
/*************data query***************************/  
$rs=$conn->query($sql);

$data=array();//Save data  
while($tmp=mysqli_fetch_assoc($rs)){//fetch a row of data from the result set each time  
    $data[]=$tmp;  
}  
// perform corresponding operations on the data  
 echo  json_encode($data);</span>

users in the database

Visit http://localhost/test/php/index.php to get the following results:

The database connection is successful. 

2.index.html file. Introduce Chart.js library and index.js file in < script > </ script > , Chart.js is a simple, object-oriented, chart drawing tool library for designers and developers. Add a canvas tag to the body tag to display the visual column chart. code show as below:

<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta http-equiv="Content-Type" charset="UTF-8" />
    <title>Case Display</title>
    <!--     <link rel="stylesheet" href="../css/ranking.css" /> -->


<style type="text/css">
	*
{
    margin: 0px;
    padding: 0px;
}

body
{
    background: #EEE;
    text-align:center;
}

#drawCanvas
{
    background: white;
    border: 1px solid #CCC;
}
</style>
</head>

<body>
    <script type="text/javascript" src="../js/Chart.js"></script>
        <script type="text/javascript" src="../js/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="../js/index.js"></script>
    <p>Class A Score Sheet</p>
    <canvas id="myChart" width="600" height="400"></canvas>
</body>

</html>

3.index.js file. Write a js function bar for drawing, with a parameter Data, and then write the getdatafromDB function to obtain the data data in the php file with ajax, and call the bar method, and call the getdatafromDB function in the window.onload function. The bar function is divided into two parts: one part is the data setting, and the other is the display style setting.

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

var getdatafromDB = function(){
	$.ajax({
		url: "../php/index.php",
		type: "POST",
		dataType:"json",
         error: function(){  
             alert('Error loading XML document');  
         },  
		success:function(data){
            console.info(data);
             bar(data);
        }
    });
}
function bar(Data)
{
    if(Data.length==null || Data.length == 0)
        return;
    var barData = {};
    barData.labels=[];
    barData.datasets=[];
    var temData = {};
    temData.data = [];
    temData.fillColor= "rgba(151,187,205,0.5)";
    temData.strokeColor = "rgba(151,187,205,0.8)";
    temData.highlightFill="rgba(151,187,205,0.75)",
    temData.highlightStroke= "rgba(151,187,205,1)";
    
    for(var i=0;i<Data.length;i++)
    {
        barData.labels.push(Data[i].label);
        temData.data.push(Data[i].value);
    }
    barData.datasets.push(temData); //Encapsulate a barData in a specified format.
    console.info (barData);
    /// animation effect
    var options = {           
        scaleOverlay: false,
        scaleOverride: false,
        scaleSteps: null,
        scaleStepWidth: null,
        scaleStartValue: null,  
        scaleLineColor: "rgba(0,0,0,.1)",  
        scaleLineWidth: 1,   
        scaleShowLabels: true,
        scaleLabel: "<%=value%>",
        scaleFontFamily: "'Arial'",   
        scaleFontSize: 12,
        scaleFontStyle: "normal",   
        scaleFontColor: "#666",
        scaleShowGridLines: true,
        scaleGridLineColor: "rgba(0,0,0,.05)",
        scaleGridLineWidth: 1,
        bezierCurve: true,
        pointDot: true,
        pointDotRadius: 3,
        pointDotStrokeWidth: 1,
        datasetStroke: true,
        datasetStrokeWidth: 2,
        datasetFill: true,
        animation: true,
        animationSteps: 60,
        animationEasing: "easeOutQuart",              
        onAnimationComplete: null
    }
    var ctx  = document.getElementById("myChart").getContext('2d');
    myChart = new Chart(ctx).Bar(barData,options, { //emphasis here
        responsive : true
    });
}

Visit http://localhost/test/html/index.html and the test results are as follows:






Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325865364&siteId=291194637